vue中修改props传进来的值浅析

众所周知,vue 是单向数据流,一般我们也不会在子组件里面修改父组件传进来的值,但总有需要修改的时候。不过值得注意的是,vue 官方不推荐直接在子组件中修改父组件传来的 props 的值。

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop’s value. Prop being mutated: “result” (found in component )

在子组件修改 props 的方法:

1.子组件 data 中拷贝一份,注意引用类型需要深拷贝,根据需求可以 watch 监听

1
2
data() { return { newList: this.list.slice() } }, watch: { list(newVal) {
this.newList = newVal } }

2.通过计算属性修改

1
2
computed: { nList() { return this.list.filter(item => { return item.isChecked })
} }

3.sync 修饰符

1
2
3
4
// 父组件
<todo-list :list.sync="list" />

// 子组件 methodName(index) { this.$emit('update:list', this.newList) }
作者

Catooilg

发布于

2020-12-08

更新于

2023-02-05

许可协议

评论