反应性损失:如何使用“深度”计算设置器

SPQ*_*Inc 6 vue.js vuejs3

我有一个模态组件,它接收一个对象作为v-model. 该对象包含一些键,例如idname

现在如果我这样做:

<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>
Run Code Online (Sandbox Code Playgroud)

console.log("computedValue?")不会触发,也不会触发发射。

如何使用“深度设置器”?

mat*_*tch 3

我为此使用的方法如下。将属性的初始“副本”作为数据变量 ( 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>
Run Code Online (Sandbox Code Playgroud)