Reputation: 90
so I'm using vue.js to render in the DOM a list of items i'm fetching from a server using an AJAX call and then I loop through a template in my html to print the labels of these items. But the problem is that after successfully fetching the data AND adding it to the array the DOM doesn't update with the new items. Here's the js code :
$(".wrench").click(function ()
{
lastClickedWrench = $(this).attr('id');
console.log("uri :" + lastClickedWrench);
var renderToolbox = new Vue({
el: "#renderToolbox",
data: function()
{
return {
listOfStuff: []
}
},
mounted: function()
{
var vueInstance = this;
$.ajax({
type: 'GET',
url: '/roles/' + lastClickedWrench,
success: function(responseData)
{
for(let i = 0; i<responseData.length; i++)
{
vueInstance.$set(vueInstance.listOfStuff, i, responseData[i].label);
//vueInstance.listOfStuff.splice(i, 1, responseData[i])
}
//vueInstance.listOfStuff = responseData;
console.log(vueInstance.listOfStuff); // this gives me the correct list
},
error: function(error)
{
console.log('error', error);
alert("error" + JSON.stringify(error));
}
});
}
});
});
All the commented out lines are solutions I tried from old stackoverflow posts which don't seem to work for me. Here's the html template :
<div id="renderToolbox">
<template v-for="item in listOfStuff">
<li class="dd-item" data-id="null">
<div class="dd-handle">
<span> {{item}} </span>
</div>
</li>
</template>
</div>
I also know about the caveat about the v-for directive which is mentioned in the documentation here : https://v2.vuejs.org/v2/guide/list.html#Caveats
I really tried everything, but nothing seems to work. Would appreciate any input on my problem.
Upvotes: 2
Views: 2224
Reputation: 501
Replace this:
vueInstance.$set(vueInstance.listOfStuff, i, responseData[i].label);
with:
this.listOfStuff.push({i:responseData[i].label})
Upvotes: 0
Reputation: 90
The problem was basically I created a new Vue for every click. The solution is to simply create the Vue once on document load.
var renderToolboxVue = new Vue({
el: "#renderToolbox",
data:
{
listOfSkills: null
},
methods:
{
fetchData: function()
{
var vueInstance = this;
$.ajax({
type: 'GET',
url: '/ascSkill/' + lastClickedWrench + '?company=' + getQueryParam("company") + '&lang=' + getQueryParam("lang"),
success: function(responseData)
{
vueInstance.listOfSkills = responseData;
},
error: function(error)
{
console.log('error', error);
alert("error" + JSON.stringify(error));
}
});
}
}
});
and have the method fetchData() that we created to be called on click like this :
$('.wrench').click(function()
{
renderToolboxVue.fetchData();
});
This will allow the Vue to update accordingly with the data passed to it.
Upvotes: 2