1
votes

I have a model in which I'm initializing an array on ajax success after the model is mounted

    var self = this;
    $.getJSON("somejson.json",
        function (data) {
            var list = [];
            list = data.list.map(function (item) {
                return { id: item.id, text: item.text };
            });

            self.selectableItems = list;
        });

I have a click method on each of these items which removes the item from selectableItems

        select: function (item) {
            this.selectableItems.pop(item);
        },

selectableItems renders correctly initially, but when I mutate the array, the dom isn't updating. Although the actual array is being modified correctly.

I verified this by having a computed property that returns the count of selectableItems. This count is updated correctly when the item is removed, but the dom still shows the item.

I also noticed that when I hard code the value of selectableItems in the ajax, everything works as expected!

self.selectableItems = [{ id: 1, text: "adsad"}];

I'm aware of the caveats of array mutation in vue. But I feel I'm missing something basic here, as I have just started exploring Vue. Can someone point out on what I'm missing?

1
Are you using Array.prototype.pop() for this.selectableItems.pop(item);? What is the argument? developer.mozilla.org/en/docs/Web/JavaScript/Reference/…choasia
ah pretty stupid of me! i was so into exploring vuejs concepts, i forgot the definition for array.pop(). Thanks anyway!.HS Krishna

1 Answers

3
votes

Array.pop() removes the last item from the array, it does not take any argument. It only removes the last item any argument you pass it.

That the reason your computed property showing the array count works as last item is being removed but not the item you want.

Use Array.splice()instead.

pass the index to your click method like this:

<ul>
    <li v-for="(item, index) in selectableItems" @click="select(index)>{{item}}</li>
</ul>

script

select: function (index) {
        this.selectableItems.splice(index, 1);
    },