vue中如何让子组件修改父组件数据

2020-06-13 10:48:22易采站长站整理

一、关于vue中watch的认识

我们要监听一个属性的的变化就使用watch一般是父组件传递给子组件的时候

•1、常见的使用场景


...
watch:{
value(val) {
console.log(val);
this.visible = val;
}
}
...

•2、如果要一开始就执行


...
watch: {
firstName: {
handler(newName, oldName) {
this.fullName = newName + '-' + this.lastName;
},
immediate: true,
}
}
...

•3、深度监听(数组、对象)


...
watch: {
obj: {
handler(newName, oldName) {
console.log('///')
},
immediate: true,
deep: true,
}
...

二、关于子组件修改父组件属性认识

在vue2.0+ 后不再是双向绑定,如果要进行双向绑定需要特殊处理。

[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: “你修改的属性名”

•1、通过事件发送给父组件来修改


**在子组件test1中**
<input type="text" v-model="book"/>
<button @click="add">添加</button>
<p v-for="(item, index) of books" :key="index">{{item}}</p>
...
methods: {
add() {
// 直接把数据发送给父组件
this.$emit('update', this.book);
this.book = '';
},
},
**在父组件中**
<test1 :books="books" @update="addBook"></test1>
...
addBook(val) {
this.books = new Array(val)
},

•2、使用.sync 来让子组件修改父组件的值(其实是上面方法的精简版)


**在父组件中,直接在需要传递的属性后面加上.sync**
<test4 :word.sync="word"/>
**在子组件中**
<template>
<div>
<h3>{{word}}</h3>
<input type="text" v-model="str" />
</div>
</template>
<script>
export default {
props: {
word: {
type: String,
default: '',
},
},
data() {
return {
str: '',
}
},
watch: {
str(newVal, oldVal) {
// 在监听你使用update事件来更新word,而在父组件不需要调用该函数
this.$emit('update:word', newVal);
}
}
}
</script>

•3、在子组件中拷贝一份副本