Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect change to modelValue in Vue 3

Tags:

vuejs3

Is there a way to detect change to modelValue in a custom component? I want to push the change to a wysiwyg editor.

I tried watching modelValue but emitting update for modelValue triggered that watch, which created circular data flow.

Code:

export default {
  props: ['modelValue'],
  watch: {
    modelValue (val) {
      this.editor.editor.loadHTML(val)
    }
  },
  mounted () {
    this.editor.editor.loadHTML(val)
    this.editor.addEventListener('trix-change', 
      (event) => this.$emit('update:modelValue', event.target.value))
  }
}
<TextEditor v-model="someHtml"></TextEditor>
like image 454
Znarkus Avatar asked Dec 30 '25 07:12

Znarkus


1 Answers

In VueJS v3, the event name for custom v-model handling changed to update:modelValue.

You can listen to these events like this: v-on:update:modelValue="handler"

For a more complete example, assume you have a Toggle component with these properties/methods:

...
props: {
        modelValue: Boolean,
},
data() {
    return {
        toggleState: false,
    };
},
methods: {
    toggle() {
        this.toggleState = !this.toggleState;
        this.$emit('update:modelValue', this.toggleState);
    }
}
...

You can use the Toggle component like this:

<Toggle v-model="someProperty" v-on:update:modelValue="myMethodForTheEvent"/>

As a side note, you could also v-model on a computed property with a setter; allowing you to internalise your state changes without using the update:modelValue event. In this example, it assumes you v-model="customProperty" on your custom Toggle component.

 computed: {
      customProperty: {
        get() {
          return this.internalProperty;
        },
        set(v) {
          this.internalProperty = v;
          console.log("This runs when the custom component 'updates' the v-model value.");
        },
      }
    },
like image 94
developerjack Avatar answered Jan 01 '26 17:01

developerjack