How to watch $attrs directive, specifically $attrs.value in Vue

Viewed 244

How do you watch $attrs.value in vue?

I have a child component:

<custom-component v-model="someData"/>

Somewhere in the parent component:

this.$emit('input', this.dataToChild)

When I update this.dataToChild in the parent component the v-model in the child component shows the corresponding changes. However I also want changes made to someData in the child component to also reflect in the parent component, such that this.dataToChild will contain whatever someData has when someData changes. I know this change is reflected to this.$attrs.value. To watch for changes I know I can use watchers in vue.

My question is what would be the syntax to watch this.$attrs.value? I know to watch a prop I can just do:

watch: {
   propToWatch: function(newVal, oldVal) {
       this.dataToChild = newVal
   }
}

I also know to watch a nested prop we can:

watch: {
    'nested.propToWatch': function(newVal, oldVal) {
        this.dataToChild = newVal
    }
}

But I'm not sure how to watch $attrs.value, would it just be:

watch: {
    '$attrs.val': function(newVal, oldVal) {
        this.dataToChild = newVal
    }
}
1 Answers

Turns out it's just like how you would do it with a nested prop, ie:

watch: {
    '$attrs.value': function(newVal, oldVal) {
        this.dataToChild = newVal
    }
}
Related