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

2024-04-01

我有一个自定义组件,它采用modelValue道具并发出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>

App.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>

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


在内部,v-model指令更改为处理函数update:modelValue事件看起来像这样:

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

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

If myArr将是一个ref([])vue 检测到它并且处理函数看起来像这样:

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

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

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

可能的解决方案:

1)使用对象键:

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

 ...

 const myArr = reactive({
    data: [1,2,3]
 });

2)使用参考:

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

 ...

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

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

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

 ...

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

 function onChange(newval){
   myArr.splice(0, myArr.length, ...newval);
 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 vue v-model 不适用于数组 prop? 的相关文章

随机推荐