这是学vue框架的小伙伴必懂的问题之一:父子组件之间的通信。
父子组件之间的关系:通常在组件Parent的模板中使用组件Child,那么此时Parent就是父组件,而Child就是子组件。
父子组件应该解耦,组件实例的作用域是孤立的,子组件中不能直接使用父组件的数据。应该使用props传递父组件到子组件的数据,子组件通过events给父组件发消息,以此实现父子组件间的通信。
一、父组件向子组件传参
- 在父组件中向子组件传入普通字符串:
<Child message="hello vue"></Child>
在子组件中用props创建一个属性,用来接收父组件传进来的参数:
props: { message: '' }
父组件需要做四件事:(1) import 引入子组件;(2) 在components中注册所有子组件的名称;(3) 在父组件的template中应用组件(例如:
<son> </son>
); (4) 如果需要传递数据给子组件就在template模板中写:<son :num=”number”></son>
还可以用v-bind动态绑定props的值到父组件的数据,父组件数据发生变化时,子组件的数据也相应的变化。
例如:
<template>
<div id="app">
<child v-bind:message="parentMsg"></child>
</div>
</template>
<script>
import child from './components/Child';
export default {
name: 'app',
data() {
return {
parentMsg:"hello,child"
}
},
components:{
child
}
}
</script>
<style>
</style>
二、子组件向父组件传参
props传递参数时是单向的,这意味着我们不能通过props向父组件传递参数。
- 子组件使用emit发送事件:
this.$emit('listenFromChildData', 'this message is from child')
父组件监听事件:
<Child @listenFromChildData="childData"></Child>
父组件一共需要做2件事情: 在template里定义事件;在methods里写函数,监听子组件的事件触发。
例如:
1.在子组件中创建一个button,给其绑定一个点击事件
<template>
<div>
<h2>child子组件部分</h2>
<p>{{message}}</p>
<button v-on:click="sendMsgToParent">向父组件传值</button>
</div>
</template>
<script>
export default{
props: ["message"],
sendMsgToParent: function(){
//do something
}
}
}
</script>
<style>
</style>
2、在响应该点击事件的函数中使用$emit来触发一个自定义事件,并传递一个参数
上述的so something 如下:
sendMsgToParent: function(){
this.$emit("listenToChildEvent","this message is from child");
}
3.在父组件中的子标签中监听该自定义事件并添加一个响应该事件的处理方法
<template>
<div id="app">
<child v-bind:message="parentMsg" v-on:listenToChildEvent="showMsgFromChild"></child>
</div>
</template>
<script>
import child from './components/Child'
export default {
name: "app",
data() {
return {
parentMsg:"hello,child"
}
},
methods: {
showMsgFromChild: function(data){
console.log(data);
}
}
}
</script>
保存,在浏览器中点击按钮:
总的来说就是:
- 子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件
- 将需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法
- 在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听
**在通信中,无论是子组件向父组件传值还是父组件向子组件传值,他们都有一个共同点就是有中间介质,子向父的介质是自定义事件,父向子的介质是props中的属性。
抓准这两点对于父子通信就好理解了**