Vuejs2 component not updating as parent data changes - vuejs2

I am trying to make a simple product catalogue using vuejs2.
All my data is stored in an object array, I then have a subset of this data which is what the product catalogue uses to display each product.The subset is used for pagination.
When a user switches pages it clears and pushes the next set of data into the array.
This automatically makes the product component display the new data.
I have issues with the following, each product has multiple colours which are stored as a comma delimited string eg (white, blue, red)
I am trying to make that information appear as a drop down list of options beside each product.
This works until I switch to the next page of data, all other details update except the colour drop downs, which only reflect the previous set of data.
My product list is stored in an object array like:
var obj = {
productID: productID,
product: title,
gender: gender,
colour: colour,
cost: cost,
size: size,
description: description
}
productArray.push(obj);
I then have several components that display this array of data:
Vue.component('product-list', {
template: '<ul id="productList">'+
'<product :productID="product.productID" v-for="product in products">'+
'<h4>Colour</h4><colourSelect :colours="product.colour" :productID="product.productID"></colourSelect>' +
'<h4>Gender</h4><span class="genderSpan"><p v-bind:id="getID(product.productID)">{{product.gender}}</p></span>' +
'</product></ul>',
data: function() {
return {
products:
paginatedArray
};
},
Vue.component('colourSelect', {
props: ['productID', 'colours'],
template: '<select v-bind:id="getID()" class="form-control input-xs"><colourOption v-for="colourItem in colourArray"></colourOption></select>',
data: function () { //split string based into array
var newArray = [];
var optionsArray = this.colours.split(',');
for (i = 0; i < optionsArray.length; i++) {
var obj = {
colour: optionsArray[i]
}
newArray.push(obj)
}
return {
colourArray: newArray
};
},
methods: {
getID: function (test) {
return 'colourSelect' + this.productID;
}
}
});
Vue.component('colourOption', {
props:['options'],
template: '<option><slot></slot></option>'
});
Within the app section of vuejs I have the following methods that do the pagination:
buildPages: function () {
for (i = 1; i < this.listLength() /this.totalPage ; i++) {
this.pages.push(i);
}
var page = this.currentPage * this.totalPage;
for (i = page; i < page + this.totalPage ; i++) {
paginatedArray.push(productArray[i]);
}
},
listLength: function () {
var listTotal = productArray.length;
return listTotal
},
changePage: function (number) {
this.currentPage = number
var page = this.currentPage * this.totalPage;
//paginatedArray = [];
var count = 0;
for (i = page; i < page + this.totalPage ; i++) {
if (typeof productArray[i] !== 'undefined') {
paginatedArray.splice(count, 1, productArray[i])
}
count++
}
},
productArray is the main array storing data, paginatedArray is the subset of data that the product component works off.
The issue appears to be within the colourSelect component, within its "data" section it splits the colour data and returns it as an colourOption component into the select, but won't update when the paginatedArray changes.
The colourSelect component does however appear to actually get passed the correct data, as getID method updates correctly. Its just the data section which is not being re-rerun.
This is my first vuejs site, anyone have any ideas around this?
Thanks

You should make the colourArray as a computed property, as the data block of component gets executed only once and later change of props will not update colourArray .
Vue.component('colourSelect', {
props: ['productID', 'colours'],
template: '<select v-bind:id="getID()" class="form-control input-xs"><colourOption v-for="colourItem in colourArray"></colourOption></select>',
computed:{
colourArray: function () { //split string based into array
var newArray = [];
var optionsArray = this.colours.split(',');
for (i = 0; i < optionsArray.length; i++) {
var obj = {
colour: optionsArray[i]
}
newArray.push(obj)
}
return newArray
}
},
methods: {
getID: function (test) {
return 'colourSelect' + this.productID;
}
}
});

Related

Calling to a method from ForEach doesn't working properly - vue.js

I'm trying to call a method from a foreach in vue, but the method is performed only one time,
No matter how many variables are in the list.
attached here the two functions I used:
CleanChips() {
this.chips.forEach((item) => {
this.RemoveRequirement(item)
})
},
RemoveRequirement(item) {
var index = this.chips.indexOf(item);
if (index > -1) {
this.chips.splice(index, 1);
this.chips = [...this.chips];
}
},
The RemoveRequirement function is performed only one time.
Any idea what's wrong here?
You modify the array itself in RemoveRequirement while running through it in CleanChips. You should create a copy of the original array to iterate in order to safely delete elements in the original array.
CleanChips() {
const chipsCopy = [...this.chips]
chipsCopy.forEach((item) => {
this.RemoveRequirement(item)
})
},
RemoveRequirement(item) {
var index = this.chips.indexOf(item);
if (index > -1) {
this.chips.splice(index, 1);
// this.chips = [...this.chips]; // you don't need this line because `splice` is reactivity-compatible.
}
},

Vue template fires more than once when used, i think i need a unique key somewhere

I am trying to implement font-awesome-picker to a website that i am making using vue2/php/mysql, but within standard js scripting, so no imports, .vue etc.
The script i am trying to add is taken from here: https://github.com/laistomazz/font-awesome-picker
The problem that i am facing is that i have 3 columns that have a title and an icon picker next it, that will allow the user to select 1 icon for each title. It is kinda working well...but if the same icon is used in 2 different columns then any time the user clicks again any of the 2 icons both instances of the picker will fire up, thus showing 2 popups. I need to somehow make them unique.
I've tried using
:key="list.id"
or
v-for="icon in icons" :icon:icon :key="icon"
but nothing worked. Somehow i have to separate all the instances (i think) so they are unique.
This is the template code:
Vue.component('font-awesome-picker', {
template: ' <div><div class="iconPicker__header"><input type="text" class="form-control" :placeholder="searchPlaceholder" #keyup="filterIcons($event)" #blur="resetNew" #keydown.esc="resetNew"></div><div class="iconPicker__body"><div class="iconPicker__icons"><i :class="\'fa \'+icon"></i></div></div></div>',
name: 'fontAwesomePicker',
props: ['seachbox','parentdata'],
data () {
return {
selected: '',
icons,
listobj: {
type: Object
}
};
},
computed: {
searchPlaceholder () {
return this.seachbox || 'search box';
},
},
methods: {
resetNew () {
vm.addNewTo = null;
},
getIcon (icon) {
this.selected = icon;
this.getContent(this.selected);
},
getContent (icon) {
const iconContent = window
.getComputedStyle(document.querySelector(`.fa.${icon}`), ':before')
.getPropertyValue('content');
this.convert(iconContent);
},
convert (value) {
const newValue = value
.charCodeAt(1)
.toString(10)
.replace(/\D/g, '');
let hexValue = Number(newValue).toString(16);
while (hexValue.length < 4) {
hexValue = `0${hexValue}`;
}
this.selecticon(hexValue.toUpperCase());
},
selecticon (value) {
this.listobj = this.$props.parentdata;
const result = {
className: this.selected,
cssValue: value,
listobj: this.listobj
};
this.$emit('selecticon', result);
},
filterIcons (event) {
const search = event.target.value.trim();
let filter = [];
if (search.length > 3) {
filter = icons.filter((item) => {
const regex = new RegExp(search, 'gi');
return item.match(regex);
});
}else{
this.icons = icons;
}
if (filter.length > 0) {
this.icons = filter;
}
}
},
});
I've setup a fiddle with the problem here:
https://jsfiddle.net/3yxk1ahb/1/
Just pick the same icon in both cases, and then click any of the icons again. You'll see that the popups opens for both columns.
How can i separate the pickers ?
problem is in your #click and v-show
you should use list.id instead of list.icon (i.e #click="addNewTo = list.id")
working fiddle https://jsfiddle.net/q513mhwt/

Vue v-for list not re-rendering after computed data update

I am implementing pagination for a huge list of cards, I display 10 cards at once and wish to show the 10 next (or 10 previous) by clicking on two buttons.
Here's how I do it:
export default {
...
data() {
return {
pois: [], // My list of elements
pageNumber: 0, // Current page number
};
},
props: {
size: {
type: Number,
required: false,
default: 10, // 10 cards per page
},
},
computed: {
pageCount() {
// Counts the number of pages total
const l = this.pois.length;
const s = this.size;
return Math.floor(l / s);
},
paginatedData() {
// Returns the right cards based on the current page
const start = this.pageNumber * this.size;
const end = start + this.size;
return this.pois.slice(start, end);
},
},
methods: {
nextPage() {
this.pageNumber += 1;
},
prevPage() {
this.pageNumber -= 1;
},
}
...
};
And my template:
<div v-for="poi in paginatedData" :key="poi.id">
<card :poi="poi"/>
</div>
Everything should work (and a page change does output the correct cards in the console) but my list is not updated even though the computed method is called on each click.
What is causing this issue? I've read it could be linked to a :key value missing, but it's there, and no data is being updated directly and manually in the array, only sliced out.
First, try this change, just for sure, and let me know in comment it works or not.
export default {
...
computed: {
paginatedData() {
...
const end = start + this.size - 1;
...
},
...
};
And yes: instead of id, try to use index:
<div v-for="(poi, idx) in paginatedData" :key="idx">
<card :poi="poi"/>
</div>

Vue computed property not updating with updated props

I'm not sure why my props aren't updating when I update the data in my parent component. I've tried it out in a fiddle and it works https://jsfiddle.net/f3w69rr6/1/ but it doesn't work in my app.
parent:
methods: {
addToHand(index) {
let card = this.gameState.playerDeck.splice(index, 1)
if (this.gameState.playerHand.length < 12)
{
// put card into hand
this.$set(this.gameState, 'playerHand', [...this.gameState.playerHand, card])
// this.gameState.playerHand.push(card)
}
// otherwise discard card
},
retrieveDeck() {
let array = []
for (let i = 0; i < 20; i++)
{
array.push(this.src + "?text=card"+i)
}
this.$set(this.gameState, 'playerDeck', array)
},
},
mounted () {
this.retrieveDeck()
for (let i = 0; i < 5; i++)
{
this.addToHand(1)
}
},
putting the data into child via:
<PlayerCards :gameState="gameState" :hand="gameState.playerHand" />
child:
export default {
name: 'PlayerCards',
props: ["gameState", "hand"],
data() {
return {
}
},
computed: {
rows() {
let cards = this.gameState.playerHand
let max = 6;
if (cards.length <= max)
return [cards]
var mid = Math.ceil(cards.length / 2);
let return_value = [cards.slice(0, mid), cards.slice(mid)]
return return_value
}
}
}
but the row content is empty.
Update (Updated fiddle):
The problem is with the compute
https://jsfiddle.net/f3w69rr6/1/
If you're not using string templates then you need to use the kebab-case equivalent to your camelCase prop:
<PlayerCards :game-state="gameState" :hand="gameState.playerHand" />
The reason it works in your fiddle is because you are using a string template (see: https://v2.vuejs.org/v2/guide/components.html#camelCase-vs-kebab-case)
Look at your demo in jsfiddle:
rows() {
let cards = this.gameState.playerHand
let max = 6;
if (cards.length <= max)
return [cards]
var mid = Math.ceil(cards.length / 2);
let return_value = [cards.slice(0, mid), cards.slice(mid)]
return return_value
}
Actually, vue has notified the computed function successfully when gameState.playerHand has updated. But you wrapped the computed property: rows into an array, like: [cards] and [cards.slice(0, mid), cards.slice(mid)]. And obviously, the rows.length will be 1 or 2.
I believe this was due to a misuse of the computed property. Switching it over to data and using this.$set updates as expected. If I were to use computed then setters would be needed. Computed also seems to be more suited for combining/updating data properties rather than being a property in and of itself.

dojo EnchancedGrid items do not select programmatically in invisible part of the view

The following code has to select items (indirect selection) programmatically, but this only happen in visible part of the table (or first 15 rows). Scrolled items remain unselected.
Is it possible to fix this?
var grid = context._events._gridView;
grid.selection.deselectAll();
var data = jsResponse.message.items;
for (var i = 0; i < data.length; ++i) {
grid.store.fetch({
query: {id: data[i].id},
onComplete: function (items)
{
dojo.forEach(items, function (item, index)
{
console.debug(item.id + "/" + index);
try {
//grid.selection.addToSelection(item);
var idx = grid.getItemIndex(item);
grid.selection.setSelected(idx,true);
}
catch (e) {
console.debug(e);
}
});
}
});
}
Using rowsPerPage, and set it to huge value, helps to work around this bug.
gridView = new dojox.grid.EnhancedGrid({
rowSelector: "20px",
rowsPerPage: plugins.indirectSelection?1500:15,
plugins: plugins
},
document.createElement('div'));