Vue.js method returning undefined when accessing data - vue.js

I'm using Vue.js to populate a list of locations, and using a method that should return a formatted map link using the address.
The problem is that in the method, trying to return this.Address ends up in undefined. Here's what I've got:
// the Vue model
pbrplApp = new Vue({
el: '#pbrpl-locations',
data: {
'success' : 0,
'errorResponse' : '',
'wsdlLastResponse' : '',
't' : 0,
'familyId' : 0,
'brandId' : 0,
'srchRadius' : 0,
'lat' : 0,
'lon' : 0,
'response' : []
},
methods: {
getDirections: function(address,city,st,zip){
// THIS Doesn't work:
//var addr = this.Address + ',' + this.City + ',' + this.State + ' ' + this.Zip;
var addr = address + ',' + city + ',' + st + ' ' + zip;
addr = addr.replace(/ /g, '+');
return 'https://maps.google.com/maps?daddr=' + addr;
}
}
});
// the template
<ul class="pbrpl-locations">
<template v-for="(location,idx) in response">
<li class="pbrpl-location" :data-lat="location.Latitude" :data-lon="location.Longitude" :data-premise="location.PremiseType" :data-acct="location.RetailAccountNum">
<div class="pbrpl-loc-idx">{{idx+1}}</div>
<div class="pbrpl-loc-loc">
<div class="pbrpl-loc-name">{{location.Name}}</div>
<div class="pbrpl-loc-address">
<a :href="getDirections(location.Address,location.City,location.State,location.Zip)" target="_blank">
{{location.Address}}<br>
{{location.City}}, {{location.State}} {{location.Zip}}
</a>
</div>
</div>
</li>
</template>
</ul>
Right now, I'm having to pass the address, city, state and zip code back to the model's method, which I know is wrong - but I can't find anything in the vue.js docs on the proper way to get the values.
What's the proper way to get the method to reference "this" properly? Thanks for your help.

this.Address doesn't work because Address is not part of your data. It looks like what you are doing is iterating through response, which somehow gets populated with locations.
You could just pass location to getDirections instead of each of the parameters.
getDirections(location){
let addr = location.Address+ ',' + location.City + ',' + location.State + ' ' + location.Zip
....
}
And change your template to
<a :href="getDirections(location)" target="_blank">
In general, in Vue methods, this will refer to the Vue itself, which means that any property that is defined on the Vue (of which properties defined in data are included) will be accessible through this (barring there being a callback inside the method that incorrectly captures this). In your case, you could refer to any of success, errorResponse, wsdlLastResponse, t, familyId, brandId, srchRadius, lat, lon, or response through this in getDirections.

Related

Render Input fields based on if field value of the field above/before Vue JS v-for/v-if

so I have a simple code of input fields which works as expected, but i try to make it more elegant.
Now my goal is to replace this first code part with a v-for / v-if condition, since i want to render up to 8 fields based on if there is an entry in the field before.
Appreciate any help.
template.js
data () {
return {
company: {
name: null,
brandName: null,
about: null,
avatar: null,
documents: null,
services: [],
serviceInitial: 1,
serviceIndex: 0,
serviceFieldCount: 8,
},}}
template.vue
<form-input
v-if="company.services[0]"
id="website"
v-model="company.services[1]"
class="company-create__input"
name="company.services"
:placeholder="$t('companyCreation.inputServicesPlaceholder') + ' ' + 2"
/>
<form-input
v-if="company.services[1]"
id="website"
v-model="company.services[2]"
class="company-create__input"
name="company.services"
:placeholder="$t('companyCreation.inputServicesPlaceholder') + ' ' + 3"
/>
and so on... up to 8 fields
My new approach which doesn't work yet:
<form-input
v-for="serviceIndex in getServiceFieldCount"
v-if="getServiceInitial + company.services[serviceIndex]>getServiceInitial"
:id="company.services[serviceIndex]"
:key="serviceIndex"
v-model="company.services[serviceIndex]"
class="company-create__input"
name="company.services"
:placeholder="$t('companyCreation.inputServicesPlaceholder')+ ' '+ serviceIndex"
/>
v-for and v-if is not gonna work in same tag , so use a span wrapper around form-input to use the v-for loop and if condition on the form-input tag
<span v-for="serviceIndex in getServiceFieldCount">
<form-input v-if="your condition"/>
</span>

Concat value into API url in Vue

I am trying something very simple in Vue and can't get it to work.. I want my API url to update with 2 new values (valueFrom and valueTwo). I am using fetch for this.
When I console log the values, they work (2021-06-17 etc). But as soon as I put them in the url, it just comes up empty.
Here are my input fields:
<label for="dateFrom" class="mr-sm-2">From</label>
<b-form-datepicker id="dateFrom" v-model="valueFrom" class="mb-2 mr-sm-4 mb-sm-0 w-25" :min="min" :max="max"></b-form-datepicker>
<label for="dateTo" class="mr-sm-2">To</label>
<b-form-datepicker id="dateTo" v-model="valueTo" class="mb-2 mr-sm-4 mb-sm-0 w-25" :min="min" :max="max"></b-form-datepicker>
Here is the button that calls the fetch:
<b-button variant="primary" #click="$fetch()">Search</b-button>
Here is my Vue code:
data() {
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const minDate = new Date(today);
const maxDate = new Date(today);
maxDate.setMonth(maxDate.getMonth() + 6);
return {
items: {},
valueFrom: '',
valueTo: '',
min: minDate,
max: maxDate
}
},
async fetch() {
const api = 'https://apiurl.com/ajax/locationSearchJSON/?location=Edinburgh&arrival=${this.valueFrom}&arrivalTime=12%3A00&departure={$this.valueTo}&departureTime=12%3A00
this.items = await fetch(api).then(res => res.json())
}
I also tried concating them in the javascript way (' + this.valueFrom + ') but that just rendered an empty string as well...
You can try using the backticks/backquotes (``) in place of the apostrophes. So your url will end up as below:
`https://apiurl.com/ajax/locationSearchJSON/?location=Edinburgh&arrival=${this.valueFrom}&arrivalTime=12%3A00&departure=${this.valueTo}&departureTime=12%3A00`
Also check the second variable this.valueTo has been added to the url correctly. In your case above this is how you've added it:
{$this.valueTo}
It should be:
${this.valueTo}

Dynamically Tally Child Elements by Classname in Vue

I have a page that allows a user to drag/drop images into pre-defined DIVs, then I tally up the total value of the images based on their class name. What I am trying to do is get vue to read the values from each outer div.answer and get the class names of the child images.
My source code is:
<div
is="box-answers"
v-for="box in boxes.slice().reverse()"
v-bind:key="box.id"
v-bind:level="box.level"
v-bind:hint="box.hint"
></div>
<script>
Vue.component('box-answers', {
props: ['level','hint'],
template: '<div class="droppable answer :id="level" :title="hint"></div>'
});
new Vue({
el: '#mainapp',
data: {
boxes: [
{ id: 1, level: 'baselevel-1', hint: 'x 1' },
{ id: 2, level: 'baselevel-2', hint: 'x 20' },
{ id: 3, level: 'baselevel-3', hint: 'x 400' },
{ id: 4, level: 'baselevel-4', hint: 'x 8,000' },
{ id: 5, level: 'baselevel-5', hint: 'x 160,000' }
]
}
</script>
This converts to the follow HTML (the nested DIVs and SPANs are user-possible entries by dragging):
<div id="baselevel-5" class="droppable answer" title="x 160,000">
<div><img src="images/line.gif" alt="Five" class="imgfive"></div>
<span><img src="images/dot.gif" alt="One" class="imgone"></span>
</div>
...
<div id="baselevel-1" class="droppable answer" title="x 1">
<span><img src="images/line.gif" alt="One" class="imgone"></span>
</div>
Currently, I have jQuery/JavaScript calculating the point values using the following:
$(function(j) {
var arAnswers = Array(1);
count = 0; //
j("div.answer").each(function( idx ) {
currentId = j(this).attr('id');
ones = 0;
fives = 0;
if ( j("#" + currentId).children().length > 0 ) {
ones = j("#" + currentId).children().find("img.imgone").length * 1;
fives = j("#" + currentId).children().find("img.imgfive").length * 5;
arAnswers[count] = ones + fives; //Tally box value
count++;
}
});
});
I would like Vue to perform similar iteration and addition to return total value of ones and fives found based on the image classname.
Currently, you are approaching this problem as a pure-play DOM operation. If that is what you need then you can simply use $refs:
<!-- NOTICE ref -->
<div ref="boxAnswers"
is="box-answers"
v-for="box in boxes.slice().reverse()"
v-bind:key="box.id"
v-bind:level="box.level"
v-bind:hint="box.hint">
</div>
Inside your high-level component, you will have a function like:
function calculate() {
// NOTICE $refs
const arAnswers = this.$refs.boxAnswers.map((x) => {
// $el is the DOM element
const once = x.$el.querySelectorAll('img.imgone').length * 1;
const fives = x.$el.querySelectorAll('img.imgfive').length * 5;
return once + fives
});
return arAnswers;
}
But this is not the correct Vue way of doing things. You have to think in terms of events and data model (MVVM - don't touch DOM. DOM is just a representation of your data model). Since, you have a drag-n-drop based application, you have to listen for drag, dragstart, dragend and other drag events. For example:
<!-- NOTICE drop event -->
<div #drop="onDropEnd(box, $event)"
is="box-answers"
v-for="box in boxes.slice().reverse()"
v-bind:key="box.id"
v-bind:level="box.level"
v-bind:hint="box.hint">
</div>
Your onDropEnd event handler will look like:
function onDrop(box, $event) {
// box - on which box drop is happening
// $event.data - which image is being dropped
// Verify $event.data is actually the image you are intending
if ($event.data === 'some-type-image') {
// Do the counting manipulations here
// ... remaining code
}
}
This is not a complete code as I don't know other components. But it should help you with the required direction.

Product autocomplete input on module (Prestashop)

I'm developing a prestashop module that has to make lists of existing products.
For the configuration panel of the module, using renderForm() and getContent(), I'm trying to replicate the "accesories" capability, where you start writing some info of a product on an input, and it shows the products that are a match. When selecting that product, it gets added on a list. Like this:
This a screenshot of Catalog / Products / Associations tab.
I'm trying with PS 1.6.0.14 and PS1.6.1.0RC3. How would I replicate this functionality to get lists of products on a module configuration panel?
I tried looking here Prestashop AdminProductsController.php but I don't really understand where half of that info is coming from.
There is an autocomplete plugin in prestashop you got to use that for this. Its in js->jquery->plugins you got to add this plugin into your module to make it work.
I think that to achieve that functionality, the renderForm() function won't be enough since you have to bind some javascript and some custom html.
The process of writing a fully functional module is a bit long but by taking the accessories functionality as a starting point it wont be so hard and you will always have a reference on "how-to-do-it".
I would go with this:
1) first create your
getContent()
function to be able to show the custom template and the product associated by your module so we will have something along:
public function getContent(){
//post process part to save the associations
if(Tools::isSubmit('saveMyAssociations'){
... //we will see it later
}
$my_associations = MyModule::getAssociationsLight($this->context->language->id,Tools::getValue('id_product')); //function that will retrieve the array of all the product associated on my module table.
$this->context->smarty->assign(array(
'my_associations' => $my_associations,
'product_id' => (int)Tools::getValue('id_product')
));
return $this->display(__FILE__, 'views/templates/admin/admintemplate.tpl'); //custome template to create the autocomplete
}
//our little function to get the already saved list, for each product we will retrieve id, name and reference with a join on the product/product_lang tables.
public static function getAssociationsLight($id_lang, $id_product, Context $context = null)
{
if (!$context)
$context = Context::getContext();
$sql = 'SELECT p.`id_product`, p.`reference`, pl.`name`
FROM `'._DB_PREFIX_.'my_associations`
LEFT JOIN `'._DB_PREFIX_.'product` p ON (p.`id_product`= `id_product_2`)
'.Shop::addSqlAssociation('product', 'p').'
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (
p.`id_product` = pl.`id_product`
AND pl.`id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('pl').'
)
WHERE `id_product_1` = '.(int)$id_product;
return Db::getInstance()->executeS($sql);
}
2) create a template that will be able to show the automplete and the list.
Here we will loop trough the saved associations to create our autocomplete list, and we will do it with some hidden field to keep track of the ids/name and also a visible list were we will have a delete button for each row.
<input type="hidden" name="inputMyAssociations" id="inputMyAssociations" value="{foreach from=$my_associations item=accessory}{$accessory.id_product}-{/foreach}" />
<input type="hidden" name="nameMyAssociations" id="nameMyAssociations" value="{foreach from=$my_associations item=accessory}{$accessory.name|escape:'html':'UTF-8'}¤{/foreach}" />
<div id="ajax_choose_product_association">
<div class="input-group">
<input type="text" id="product_autocomplete_input_association" name="product_autocomplete_input_association" />
<span class="input-group-addon"><i class="icon-search"></i></span>
</div>
</div>
<div id="divMyAssociations">
{foreach from=$my_associations item=accessory}
<div class="form-control-static">
<button type="button" class="btn btn-default delAssociation" name="{$accessory.id_product}">
<i class="icon-remove text-danger"></i>
</button>
{$accessory.name|escape:'html':'UTF-8'}{if !empty($accessory.reference)}{$accessory.reference}{/if}
</div>
{/foreach}
</div>
<input type="submit" name="submitMyAssociations" id="submitMyAssociations" value="Send"/>
<input type="hidden" name="productId" id="productId" value="{$product_id|escape:'html'}"/>
3) Now we can add the javascript to bind an autocomplete on the main input and perform all the logic for each action
$(document).ready(function(){
//our function wrapper.
var initMyAssociationsAutocomplete = function (){
//initialize the autocomplete that will point to the default ajax_products_list page (it returns the products by id+name)
$('#product_autocomplete_input_association')
.autocomplete('ajax_products_list.php', {
minChars: 1,
autoFill: true,
max:20,
matchContains: true,
mustMatch:true,
scroll:false,
cacheLength:0,
formatItem: function(item) {
return item[1]+' - '+item[0];
}
}).result(addAssociation);
//as an option we will add a function to exclude a product if it's already in the list
$('#product_autocomplete_input_association').setOptions({
extraParams: {
excludeIds : getAssociationsIds()
}
});
};
//function to exclude a product if it exists in the list
var getAssociationsIds = function()
{
if ($('#inputMyAssociations').val() === undefined)
return '';
return $('#inputMyAssociations').val().replace(/\-/g,',');
}
//function to add a new association, adds it in the hidden input and also as a visible div, with a button to delete the association any time.
var addAssociation = function(event, data, formatted)
{
if (data == null)
return false;
var productId = data[1];
var productName = data[0];
var $divAccessories = $('#divCrossSellers');
var $inputAccessories = $('#inputMyAssociations');
var $nameAccessories = $('#nameMyAssociations');
/* delete product from select + add product line to the div, input_name, input_ids elements */
$divAccessories.html($divAccessories.html() + '<div class="form-control-static"><button type="button" class="delAssociation btn btn-default" name="' + productId + '"><i class="icon-remove text-danger"></i></button> '+ productName +'</div>');
$nameAccessories.val($nameAccessories.val() + productName + '¤');
$inputAccessories.val($inputAccessories.val() + productId + '-');
$('#product_autocomplete_input_association').val('');
$('#product_autocomplete_input_association').setOptions({
extraParams: {excludeIds : getAssociationsIds()}
});
};
//the function to delete an associations, delete it from both the hidden inputs and the visible div list.
var delAssociations = function(id)
{
var div = getE('divMyAssociations');
var input = getE('inputMyAssociations');
var name = getE('nameMyAssociations');
// Cut hidden fields in array
var inputCut = input.value.split('-');
var nameCut = name.value.split('¤');
if (inputCut.length != nameCut.length)
return alert('Bad size');
// Reset all hidden fields
input.value = '';
name.value = '';
div.innerHTML = '';
for (i in inputCut)
{
// If empty, error, next
if (!inputCut[i] || !nameCut[i])
continue ;
// Add to hidden fields no selected products OR add to select field selected product
if (inputCut[i] != id)
{
input.value += inputCut[i] + '-';
name.value += nameCut[i] + '¤';
div.innerHTML += '<div class="form-control-static"><button type="button" class="delAssociation btn btn-default" name="' + inputCut[i] +'"><i class="icon-remove text-danger"></i></button> ' + nameCut[i] + '</div>';
}
else
$('#selectAssociation').append('<option selected="selected" value="' + inputCut[i] + '-' + nameCut[i] + '">' + inputCut[i] + ' - ' + nameCut[i] + '</option>');
}
$('#product_autocomplete_input_association').setOptions({
extraParams: {excludeIds : getAssociationsIds()}
});
};
//finally initialize the function we have written above and create all the binds.
initMyAssociationsAutocomplete();
//live delegation of the deletion button to our delete function, this will allow us to delete also any element added after the dom creation with the ajax autocomplete.
$('#divMyAssociations').delegate('.delAssociation', 'click', function(){
delAssociations($(this).attr('name'));
});
});
4) now you just need to save the associations made by your module autocomplete, and i suggest to perform it by first deleting any association made on a given product and then saving all of them. so you don't have to care about inserting or updating an entry
public function getContent(){
//post process part
if(Tools::isSubmit('saveMyAssociations'){
$product_id = (int)Tools::getValue('productId');
// see the function below, a simple query to delete all the associations on a product
$this->deleteMyAssociations($product_id);
if ($associations = Tools::getValue('inputMyAssociations'))
{
$associations_id = array_unique(explode('-', $associations));
if (count($associations_id))
{
array_pop($associations_id);
//insert all the association we have made.
$this->changeMyAssociations($associations_id, $product_id);
}
}
}
}
protected function deleteMyAssociations($product_id){
return Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'my_associations` WHERE `id_product_1` = '.(int)$product_id);
}
protected function changeMyAssociations($associations_id, $product_id){
foreach ($associations_id as $id_product_2)
Db::getInstance()->insert('my_associations', array(
'id_product_1' => (int)$product_id,
'id_product_2' => (int)$id_product_2
));
}
I hope it can help you to go through all of this.

How do I send an additional parameter to a function?

I have this code which displays text from a Web SQL database:
<span contenteditable="true"
onkeyup="updateRecord('+item['id']+', this)">' + item['product'] + '</span>
When I edit the text it calls the updateRecord function and updates the value.
function updateRecord(id, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE products SET product = ? WHERE id = ?",
[textEl.innerHTML, id], null, onError);
});
}
I have several of these values I'm trying to work with though. So I would like to specify the column. The above code works if I set the column to product in the function, in the following code I'm trying to send an additional parameter to the function but it's not working. What am I doing wrong here?
<span contenteditable="true"
onkeyup="updateRecord('+item['id']+', 'product', this)">'+ item['product'] + '</span>
function updateRecord(id, column, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE products SET ? = ? WHERE id = ?",
[column, textEl.innerHTML, id], null, onError);
});
}
Same with any full-bodied DBMS, you cannot parameterize the column names, only values.
So you need to do it like this
<span contenteditable="true"
onkeyup="updateRecord('+item['id']+', 'product', this)">'+ item['product'] + '</span>
function updateRecord(id, column, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE products SET " + column + " = ? WHERE id = ?",
[column, textEl.innerHTML, id], null, onError);
});
}