为什么 vue v-model 不适用于数组 prop?

Cod*_*iwi 4 javascript vue.js vue-reactivity vuejs3 vue-composition-api

我有一个自定义组件,它接受modelValueprop 并发出update:modelValue事件。在父组件中,我传递一个数组:

测试组件.vue

<template>
  <div>
     <button @click="updateIt">Test</button>
  </div>
</template>

<script>
export default {
    props: {
       modelValue: Array
    },
    emits: ["update:modelValue"],
    setup(props, {emit}){
        return {
            updateIt(){
                emit("update:modelValue", [4,5,6])
            }
        }
    }
}
</script>
Run Code Online (Sandbox Code Playgroud)

应用程序.vue

<template>
  <div>
     <test-component v-model="myArr"/>
     <ul>
         <li v-for="i in myArr" v-text="i"></li>
     </ul>
  </div>
</template>

<script>
import TestComponent from "./TestComponent.vue";

export default {
    components: {
        TestComponent
    },
    setup(props, {emit}){
        const myArr = reactive([1,2,3]);

        return {
            myArr
        }
    }
}
</script>
Run Code Online (Sandbox Code Playgroud)

当我按下按钮时,列表不会更新,为什么?

Cod*_*iwi 5

在内部,该v-model指令被更改为update:modelValue事件的处理函数,如下所示:

$event => ((exp => $event)其中 exp 是指令中的表达式

这基本上意味着,当update:modelValue事件被发出时,您发出的值会直接分配给myArr变量,从而有效地替换整个reactive变量,而不会触发反应链,因为它不是通过代理发生的。

如果myArrvueref([])检测到它,处理函数看起来像这样:

$event => (exp ? (exp).value = $event : null)其中 exp 是指令中的表达式

这意味着该值是通过引用代理分配的,从而触发反应链。

但是没有内部逻辑来检查传递的表达式是否是数组,如果是,是否进行一些拼接推送魔法来保留原始变量,您必须自己执行此操作。

可能的解决方案:

1)使用对象键:

 <test-component v-model="myArr.data"/>

 ...

 const myArr = reactive({
    data: [1,2,3]
 });
Run Code Online (Sandbox Code Playgroud)

2)使用参考:

 <test-component v-model="myArr"/>

 ...

 const myArr = ref([1,2,3]);
Run Code Online (Sandbox Code Playgroud)

3)使用自定义处理函数:

 <test-component :modelValue="myArr" @update:modelValue="onChange"/>

 ...

 const myArr = reactive([1,2,3]);

 function onChange(newval){
   myArr.splice(0, myArr.length, ...newval);
 }
Run Code Online (Sandbox Code Playgroud)