我有一个模态组件,它接收一个对象为 v-model
.此对象包含一些键,如 id
或 name
.
现在,如果我这样做:
<template>
<div class="h-2/3 w-2/3 bg-green-500">
<input v-model="computedValue.id" />
{{computedValue}}
</div>
</template>
<script>
export default {
name: 'TestModal',
props: {
modelValue: {
type: Object,
},
},
emits: ["update:modelValue"],
data: () => ({
}),
computed: {
computedValue: {
get() {
return this.modelValue;
},
set(newValue) {
console.log("computedValue?")
this.$emit('update:modelValue', newValue)
}
},
},
methods: {
},
}
</script>
console.log("computedValue?")
永远不会触发,也不会触发发射。如何使用“深二传手”?
最佳答案
我为此使用的方法如下。将属性的初始“副本”作为数据变量 ( rwModel
)。使用 v-model
与此变量进行交互,然后使用观察器在变量更改时触发事件/做一些工作。
优点是您从不尝试修改属性,但您也会尽量避免这种情况,因此它仍然易于测试和理解。您还可以在观察者中获取旧值,这使得比较变得容易。
或者,您可以轻松地修改它,而不是观看,以触发对更新数据执行某些操作的事件 - 例如表单上的保存按钮。
<template>
<div class="h-2/3 w-2/3 bg-green-500">
<input v-model="rwModel.id" />
{{rwModel}}
</div>
</template>
<script>
export default {
props: {
modelValue: {
type: Object,
},
},
emits: ["update:modelValue"],
data() {
return {
rwModel: this.modelValue,
}
},
watch: {
modelValue: {
deep: true,
handler(newValue) {
console.log("watchedValue?")
this.$emit('update:modelValue', newValue)
},
},
},
}
</script>
关于vue.js - react 性丢失 : How to use a "deep" computed setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69198771/