vue组件之间的传值
1.父子之间的传值:
1》父传给子:通过props属性
2》子传给父:通过事件触发,$emit
2.兄弟组件之间的传值:
定一个一个eventBus.js文件,内容如下:
import Vue from 'vue' const Bus = new Vue(); export default Bus
定义第一个兄弟组件:firstChildren.vue:内容如下:
<template> <div> <h3>firstChildren向其他兄弟组件传值</h3> <button v-on:click="sendMsg"组件传值></button> </div> </template> <script> import bus from '@assets/js/eventBus' export default { methods:{ sendMsg(){ bug.$emit('childrenEvent','this msg is from firstChild') } } } </script>
再定义另外一个兄弟组件去接收传过来的值:secondChildren:
<template> <div> <h3>secondChildren组件</h3> <p>组件传值{{msg}}</p> </div> </template> <script> import bus from '@assets/js/eventBus' export default { data(){ return { msg:'hello world' } }, methods:{ sendMsg(){ bug.on('childrenEvent',(msg)=>{ this.msg = msg || 'hello world' }) } } } </script>