20201016岳浩天
学习知识
组件通信(父子通信)
<body>
<div id="app">
<h1>{{des}}</h1>
<component-a :father="des" @handone="handchange"></component-a>
</div>
<script src="./js/vue.js"></script>
<script>
new Vue({
el: '#app',
data() {
return {
des: '父亲的数据'
}
},
methods: {
handchange(data) {
console.log(data);
}
},
components: {
componentA: {
template: `
<div>
<h1>这是子组件</h1>
<h2>{{father}}</h2>
<button @click='hand'>点击</button>
</div>
`,
data() {
return {
children: '1'
}
},
props: ['father'],
methods: {
hand() {
this.$emit('handone', this.children)
}
},
}
}
})
</script>
</body>
总结:
父传子:①子组件需要创建一个值动态绑定父组件传来的值
②props接受值
③使用
子传父:因为子传父是被动触发
所以①子组件需要先触发一个事件 然后在事件中使用自带的$emit方法
②子组件自定义事件
③父组件监听子组件第一的事件,并用一个方法接收
近期评论