首页 > 解决方案 > 在 Vue 3 中检测对 modelValue 的更改

问题描述

有没有办法检测自定义组件中对 modelValue 的更改?我想将更改推送到所见即所得的编辑器。

我尝试观看 modelValue 但为 modelValue 发出更新触发了该手表,从而创建了循环数据流。


代码:

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>

标签: vuejs3

解决方案


在 VueJS v3 中,自定义 v-model 处理的事件名称更改为“update:modelValue”。

您可以像这样收听这些事件:v-on:update:modelValue="handler"

对于更完整的示例,假设您有一个具有以下属性/方法的 Toggle 组件:

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

您可以使用该切换组件:

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

作为旁注,您还可以使用 setter 对计算属性进行 v-model ;允许您在不使用 update:modelValue 事件的情况下内化您的状态更改。在此示例中,它假定您v-model="customProperty"使用自定义 Toggle 组件。

 computed: {
      customProperty: {
        get() {
          return this.internalProperty;
        },
        set(v) {
          this.internalProperty = v;
          console.log('This runs when the custom component 'updates' the v-model value.);
        },
      }
    },

推荐阅读