Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js 2 - $forceUpdate() on components doesn't refresh computed properties?

Tags:

vue.js

I'm not sure if I'm doing this right or wrong, but all the answers I seem to find how to update the dom for computed values...

I have this component:

Vue.component('bpmn-groups', {
    props: ['groups', 'searchQuery'],
    template: '#bpmn-groups',
    computed: {
        filteredGroups: function () {
            var self = this;
            return this.groups.filter(function(group) {
                self.searchQuery = self.searchQuery || '';
                return _.includes( group.name.toLowerCase(), self.searchQuery.toLowerCase() );
            });
        }
    },
    methods: {
        clearFilter: function () {
            this.searchQuery = '';
        },
        deleteGroup: function(group) {
            Vue.http.delete('api/groups/'+group.id ).then(response => { // success callback
                var index = this.groups.indexOf(group); // remove the deleted group
                this.groups.splice(index, 1);
                this.$forceUpdate(); // force update of the filtered list?
                toastr.success('Schemų grupė <em>'+group.name+'</em> sėkmingai pašalinta.');
            }, response => { // error callback
                processErrors(response);
            });
            this.$forceUpdate();
        },
    },
});

And in the template I just have a simple v-for to go through filteredGroups:

<input v-model="searchQuery" type="text" placeholder="Search..." value="">
<div v-for="group in filteredGroups" class="item">...</div>

The deletion works fine, it removes it from groups property, however the filteredGroups value still has the full group, until I actually perform a search or somehow trigger something else...

How can I fix it so that the filteredGroup is updated once the group is updated?

like image 351
GTMeteor Avatar asked Feb 17 '17 14:02

GTMeteor


1 Answers

Don't mutate a prop - they are not like data defined attributes. See this for more information:

https://v2.vuejs.org/v2/guide/components.html#One-Way-Data-Flow

Instead, as recommended in the link, declare a local data attribute that is initialized from the prop and mutate that.

like image 173
David K. Hess Avatar answered Oct 22 '22 20:10

David K. Hess