vuejs3 - 在 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>
解决方案
在 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.);
},
}
},
推荐阅读
- javascript - 键移动后缩放翻译问题
- html - 如何在 Angular 中定位材质菜单?
- django - Django + Gunicorn + Nginx。404
- angular - 如何在Angular中将按钮添加到循环的最后一个组件
- python - Spyder 4.1.5 中不支持没有形状的对象数组问题
- javascript - 编写一个基于 JS 中的输入数组创建动态输出的函数
- regex - 在 Bigquery 中使用正则表达式获取地址的街道名称和编号
- python - 是否可以使用 Selenium 与通过请求访问的网页进行交互?
- r - 带有 scale_y_continuous() 的多面直方图中的百分比
- python - 加权稀疏分类交叉熵