以下面代码为例,组件内部不能直接去改变 props 的值,
但是,如果 prop 的值是数组,可以改,不过 eslint 会标红,建议最好不要这样写 Unexpected mutation of "list" prop.eslintvue/no-mutating-props
所以应该如何修改呢?
如果用 watch 监听,似乎又会很耗性能,还有没有什么好的办法呢?
父组件 index.vue
<!-- 父组件 index.vue -->
<template>
<view>
<Add :list="addList"></Add>
<button @click='add'>添加</button>
</view>
</template>
<script setup>
import { ref } from 'vue';
const addList = ref([]);
const add = () => {
addList.value.push('abc');
}
</script>
<style></style>
子组件 Add.vue
<!-- 子组件 Add.vue -->
<template>
<view>
<view v-for="(item, idx) in list" :key="idx" class="add">
{{ item }}<button @click="del(idx)">删除</button>
</view>
</view>
</template>
<script setup>
const props = defineProps({
list: {
type: Array,
default() {
return [];
},
},
});
const del = (idx) => {
props.list.splice(idx, 1);
};
</script>
<style lang="scss" scoped>
.add {
display: flex;
flex-direction: row;
}
</style>