1

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')
    }
 }
2
  • 2
    Isn't this just example c from the docs? vuejs.org/v2/api/#watch Commented Sep 25, 2019 at 7:01
  • Ah, You're right. Thank you so much for your inspiration. Commented Sep 25, 2019 at 7:17

1 Answer 1

1

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')
        }
    }
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Adding a watcher for a computed property counts as 'using' it. You don't have to use it somewhere else for the watcher to be called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.