目录
app开发定制组件数据共享
app开发定制组件之间的关系:在项目开发中,组件之间的最常用的关系分为两种:父子关系和兄弟关系。
父组件向子组件共享数据
通过实现父向子传值。
子组件向父组件共享数据
通过自定义事件实现子向父传值
兄弟组件共享数据
在 .x中,兄弟组件之间数据共享方案是 EventBus。
EventBus的使用步骤:
1)创建.js模块,并向外共享一个Vue的实例对象
- import Vue from 'vue'
- // 向外共享 Vue 的实例对象
- export default new Vue()
2)在数据发送方,调用bus.$emit('事件名称',要发送的数据)方法触发自定义事件
- <template>
- <div class="left-container">
- <h3>Left组件--{{count}}</h3>
- <button @click="send">点击给Right发送数据</button>
- </div>
- </template>
- <script>
- // 1.导入 eventBus.js 模块
- import bus from './eventBus'
- export default{
- data(){
- return {
- // 兄弟组件要传送的数据
- str:'我想对你说:hello world'
- }
- },
- methods:{
- send(){
- // 2.通过eventBus来发送数据
- bus.$emit('share',this.str)
- }
- }
- }
- </script>
- <style lang="less" scoped>
- h3{
- color: #f00;
- }
- .left-container{
- padding: 0 20px 20px;
- background-color: orange;
- min-height: 250px;
- flex: 1;
- }
- ::v-deep h5{
- color:#00f
- }
- </style>
3)在数据接受方,调用bus.$on('事件名称',事件处理函数)方法注册一个自定义事件
- <template>
- <div class="right-container">
- <h3>Right组件</h3>
- {{msgFromLeft}}
- </div>
- </template>
- <script>
- // 1.导入 eventBus.js 模块
- import bus from './eventBus'
- export default{
- data(){
- return {
- // 兄弟组件要接受的数据
- msgFromLeft:""
- }
- },
- created(){
- bus.$on('share',val=>{
- this.msgFromLeft = val
- // console.log('在Right组件中定义的share被触发了!',val);
- })
- }
- }
- </script>
- <style>
- .right-container{
- padding: 0 20px 20px;
- background-color: orange;
- min-height: 250px;
- flex: 1;
- }
- </style>