检测 Vue 3 中 modelValue 的更改

Zna*_*kus 12 vuejs3

有没有办法检测自定义组件中 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))
  }
}
Run Code Online (Sandbox Code Playgroud)
<TextEditor v-model="someHtml"></TextEditor>
Run Code Online (Sandbox Code Playgroud)

dev*_*ack 13

在 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);
    }
}
...
Run Code Online (Sandbox Code Playgroud)

您可以使用该 Toggle 组件:

<Toggle v-model="someProperty" v-on:update:modelValue="myMethodForTheEvent"/>
Run Code Online (Sandbox Code Playgroud)

附带说明一下,您还可以使用 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.");
        },
      }
    },
Run Code Online (Sandbox Code Playgroud)


Fil*_*ger 11

我遇到了同样的问题,并通过稍微调整调用函数的方式解决了它watch

setup(props) {
      watch(() => props.modelValue, (newValue) => {
            // do something
      })
}
Run Code Online (Sandbox Code Playgroud)

因此,重要的是添加() => props.modelValue而不是仅仅将其props.modelValue作为函数的第一个参数watch