1

i have array inside object

    Vue.component('greeting', {
      template: '<button @click="cool">getdate! </button> ',
      data :function () {
        return {
          message:"15/10/1999",
        }
      },
      methods:{
        cool(){
          this.$parent.info.date.push(this.message);
        }
      }
    });
    
    
    var vm = new Vue({
      el: '#app',
      data:{
      name:"",
        info:{
          date:[]
        }
      }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
      <greeting></greeting>
      {{info.date}}
    </div>

I sent date from component it works fine but watch won't work.

how to use watch in this case in vuejs

1 Answers1

0

The Vue way to do this is emit an event from your component to its parent. This honours Vue's one-way data-flow concept.

If you want to have some data property change when another does, I recommend using a computed property instead of a watch.

For example...

Vue.component('greeting', {
  template: '<button @click="cool">getdate!</button> ',
  data () {
    return {
      message: "15/10/1999"
    }
  },
  methods:{
    cool(){
      this.$emit('click', this.message)
    }
  }
});

new Vue({
  el: '#app',
  data:{
    info:{
      date: []
    }
  },
  methods: {
    addDate (date) {
      this.info.date.push(date)
    }
  },
  computed: {
    name () {
      return this.info.date.length ? 'Jack' : ''
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js"></script>
<div id="app">
  <greeting @click="addDate"></greeting>
  <pre>info = {{ info }}</pre>
  <pre>name = {{ name }}</pre>
</div>
tony19
  • 125,647
  • 18
  • 229
  • 307
Phil
  • 157,677
  • 23
  • 242
  • 245