参考https://mp.weixin.qq.com/s/GqIR5XrtlYVEF70q1lkDag
自己补充
父组件
<template> <div class="wrapper"> <button @click="change">我是父组件</button> <div>{{msg.name}}</div> <div class="list1"> <list1 v-show="isShow" :isShow.sync="isShow" :msg.sync="msg" /> </div> <div class="list2"> <list2 /> </div> </div> </template> <script> import list1 from './list1.vue'; import list2 from './list2.vue'; export default { components: { list1, list2 }, props: {}, data() { return { isShow: false, msg: { name: '我是父组件的msg', id: '父级1' } }; }, watch: { msg: { handler(newName, oldName) { console.log('父组件', newName); }, immediate: true, //true时,第一次加载也会监听到,其实就是data里面的值 deep: true //深度监听,可以监听到类似于vuex里面对象的属性变动 } }, computed: {}, methods: { change() { this.isShow = !this.isShow; this.msg = { name: '我是父组件的msg', id: '父级1' }; } }, created() {}, mounted() {} }; </script> <style scoped lang='less'> .wrapper { } .list1, .list2 { width: 100%; height: 100px; //background: orange; display: flex; text-align: center; align-items: center; font-size: 20px; justify-content: center; } </style>
子组件
<template> <div class="wrapper"> 我是list1 <input type="button" value="点我隐身" @click="upIsShow"> <input type="button" value="点我msg" @click="changeMsg"> </div> </template> <script> export default { components: {}, props: { msg: { type: Object } }, data() { return { msg_son: { name: '我是子组件的msg', id: '子级1' } }; }, watch: {}, computed: {}, methods: { upIsShow() { this.$emit('update:isShow', false); }, changeMsg() { this.$emit('update:msg', this.msg_son); } }, created() {}, mounted() { //console.log(this.msg); } }; </script> <style scoped> .wrapper { } </style>
1:props
最好写成对象带type类型这种,比较严谨
2上面其实也展现了父子组件通信,只不过多了sync
子组件想修改数据并且同步更新到父组件的作用;
解析:父组件把msg通过v-bind传到了子组件,子组件通过props去接收;获取到了父组件的参数;然后子组件通过事件触发,$emit去绑定一个事件,就可以把值传到了父组件种;
这里之所以用this.$emit('update:isShow', false);这种情况,是因为父组件的.sync做了语法糖的简化
关于sync的详细解释可以参考https://www.jianshu.com/p/d42c508ea9de