Otonel
Otonel

Reputation: 117

Vue.js watch not triggering when object is modified

In Vue.js I have three templates that should work together to trigger loading of new results. My container template is a general template that contain the filters and the results templates. I am having some difficulties with making watch() trigger changes in my results template when an object is changed in the filters template. The flow is quite simple. Here is what I have at the moment and how the flow works:

Filters template: on click my object property is updated with a new value and emit this change to the container template.

<span v-on:click='setClient(client.ccid)'>{{client.name}}</span>
data: function() {
    return {
        formData: {
            perPage: 15,
            clientId: null
        }
    }
}

setClient: function(clientId){
  this.formData.clientId = clientId;
  this.$emit('filters-update', this.formData);
}

Container template: - this has just the role to hold the filters and results template and pass the modified object to the results template.

<template>
   <div class="row">
     <filters v-on:filters-update="filtersUpdate"></filters>
     <results :filters='filters'></results>
   </div>
</template>

<script>
export default {
    data: function() {
       return  {
          filters: {}
       }
    },

    methods: {
        filtersUpdate: function(params){
            this.filters = params;
        }
    }
}
</script>

Results template:

export default {
  props: {
    filters: {
        type: Object
    },
  }
}

watch: {
  filters: function(){
    console.log("loading new results..");
    this.loadData();
  }
}

Upvotes: 2

Views: 3599

Answers (1)

Otonel
Otonel

Reputation: 117

Apparently to watch over object properties change, you need a deep watch https://v2.vuejs.org/v2/api/#watch

watch: {
    filters: {
        deep: true,
        handler(){
            this.loadData();
        }
    }
}

Upvotes: 2

Related Questions