vue component data watch outside vue component data watch outside vue.js vue.js

vue component data watch outside


The standard practice would be to emit an event in the child and have the parent receive and act on it. You might wonder whether you can watch the length of an array -- one that doesn't even exist when the component is instantiated -- and the answer is yes.

Look at the watch section. IMO, this is so cool that it's probably frowned upon.

Vue.component('vue-table', {  template: '<div><template v-for="row in apiData.content"><span>{{row.name}}</span><button @click="remove(row)">remove</button><br></template></div>',  data: function() {    return {      //this data will be loaded from api       apiData: {},    };  },  methods: {    remove(row) {      this.apiData.content.splice(this.apiData.content.indexOf(row), 1);    },  },  watch: {    'apiData.content.length': function(is, was) {      this.$emit('content-length', is);    }  },  created() {    this.apiData = {      total: 20,      content: [{        id: 10,        name: 'Test'      }, {        id: 12,        name: 'John'      }, {        id: 13,        name: 'David'      }, ],    };  }})new Vue({  el: '#app',  data: {    isActive: false  },  methods: {    setActive(contentLength) {      this.isActive = contentLength > 0;    }  },})
#app {  font-family: 'Avenir', Helvetica, Arial, sans-serif;  -webkit-font-smoothing: antialiased;  -moz-osx-font-smoothing: grayscale;  text-align: center;  color: #2c3e50;  margin-top: 60px;}.active {  font-weight: bold;}
<script src="//unpkg.com/vue@latest/dist/vue.js"></script><div id="app">  <p>    <span :class="{active: isActive}">Users:</span>  </p>  <vue-table refs="table" @content-length="setActive"></vue-table></div>