这篇文章给大家分享的是有关vue中如何实现让子组件修改父组件数据的方法的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。
一、关于vue中watch的认识
我们要监听一个属性的的变化就使用watch一般是父组件传递给子组件的时候
•1、常见的使用场景
...
watch:{
value(val) {
console.log(val);
this.visible = val;
}
}
...
相关学习推荐:javascript视频教程
•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>
<p>
<h4>{{word}}</h4>
<input type="text" v-model="str" />
</p>
</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、在子组件中拷贝一份副本
**子组件中**
export default {
props: {
// 已经选中的
checkModalGroup: {
type: Array,
default: [],
required: false,
}
},
data() {
return{
copyCheckModalGroup: this.checkModalGroup, // 选中的
}
},
methods: {
// 一个一个的选择
checkAllGroupChange(data) {
// 把当前的发送给父组件
this.$emit('updata', data);
},
},
watch: {
checkModalGroup(newVal, oldVal) {
this.copyCheckModalGroup = newVal;
}
}
}
**父组件中直接更新传递给子组件的数据就可以**
...
// 更新子组件数据
roleCheckUpdata(data) {
this.roleGroup = data;
},
...
感谢各位的阅读!关于vue中如何实现让子组件修改父组件数据的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。