DD DD
DD DD

Reputation: 1228

How to use 'deep method' in vuejs

I have a vue component like below.
And I want to use watch for a specific keyword not everything.
So I made a computed function to focus it.
The code below works very well.

var vm = new Vue({
  el: '#app',
  computed: {
    foo() {
      return this.item.foo;
    }
  },
  watch: {
    foo() {
      console.log('Foo Changed!');
    }
  },
  data: {
    item: {
      foo: 'foo'
    }
  }
})

And I applied to my example. In this case, it doesn't work well. So I guess it should be used by 'deep: true' inside of 'changedOptions' of watch. But I don't know how can I use 'deep' inside of a function.Could you recommend some solutions?

data(){
   return {
       deliveryOptions: {
           weight: 3,
           options: { express: false, shuttle: false, bike: true, walk: false },
   },



 computed: {changedOptions() {
             return this.deliveryOptions.options;
            }
 },

 watch: {
    changedOptions(){
        console.log('changed')
    }
 }

Upvotes: 1

Views: 238

Answers (1)

Asim Khan
Asim Khan

Reputation: 2039

Computed only runs when you use computed value somewhere.

you can either use it in the template part or in the script.

lets us use it in mounted like below

mounted () {
  console.log(this.changedOptions)
  // this will call the computed to return the value.
}

if the watcher still doesn't run then you can try immediate: true in watcher like below

 watch: {
    changedOptions: {
       immediate: true, 
       handler () {
          console.log('changed')
        }
    }
 }

Upvotes: 1

Related Questions