组件间的通信有两种:1、父组件与子组件之间的通信;2、非父子组件间通信;
一、父组件与子组件之间的通信
父组件传递数据给子组件(使用props):
父组件:
<template>
<div style="width:100%">
<child :showMessageContent="childMessage"></child>
</div>
</template>
<script type="text/javascript">
export default {
name: 'parent',
data: {
childMessage:'mmm'
}
}
</script>
子组件:
<template> <div style="text-align: left;padding:20px;font-size:14px;color:blue;"> <p>{{showMessageContent}}</p> </div> </template> <script type="text/javascript"> export default { name: 'child', props: { showMessageContent:{ type: String, default: '' } } } </script>
子组件传递数据给父组件($emit触发父组件的方法进行数据通信):
父组件:
<template> <div style="width:100%"> <child :showMessageContent="childMessage" @showHello="hello"></child> </div> </template> <script type="text/javascript"> export default { name: 'parent', data: { childMessage:'mmm' }, methods:{ hello(data){ console.log('data',data); } } } </script>
子组件:
<template> <div style="text-align: left;padding:20px;font-size:14px;color:blue;"> <p @click="helloParent">{{showMessageContent}}</p> </div> </template> <script type="text/javascript"> export default { name: 'child', props: { showMessageContent:{ type: String, default: '' } }, methods:{ helloParent(){ this.$emit('showHello','xxx'); } } } </script>
p元素上增加点击事件,通过$emit 触发父组件的方法进行通信。
控制台打印结果:
子组件向父组件通信还可以通过$.dispatch,自己未用过此种方式,后续对此进行补充。
二、非父子组件间通信($emit,$on)
例子目的:组件A的信息传递给组件B
创建一个公共js文件,设计一条总线,即一个事件中心(中转站)。
//创建bus.js文件 import Vue from "vue"; export default new Vue();
组件A:
import Bus from '../common/bus.js'; export default { name: 'A', data () { return { msg: 'message A' } }, methods:{ sendByClick(){ Bus.$emit('send',this.msg); } } }
组件B:
import Bus from '../common/bus.js'; export default { name: 'B', data () { return { msgB: '' } }, mounted:function(){ let _this = this; Bus.$on('send', function(msg){ _this.msgB = msg ; console.log(_this.msgB); }); } }
控制台打印结果:
收获纪录?