app开发定制Vue--》简述组件的数据共享

目录


app开发定制组件数据共享

app开发定制组件之间的关系:在项目开发中,组件之间的最常用的关系分为两种:父子关系和兄弟关系。

父组件向子组件共享数据

通过实现父向子传值。

子组件向父组件共享数据

通过自定义事件实现子向父传值

兄弟组件共享数据

在 .x中,兄弟组件之间数据共享方案是 EventBus。

EventBus的使用步骤

1)创建.js模块,并向外共享一个Vue的实例对象

  1. import Vue from 'vue'
  2. // 向外共享 Vue 的实例对象
  3. export default new Vue()

2)在数据发送方,调用bus.$emit('事件名称',要发送的数据)方法触发自定义事件

  1. <template>
  2. <div class="left-container">
  3. <h3>Left组件--{{count}}</h3>
  4. <button @click="send">点击给Right发送数据</button>
  5. </div>
  6. </template>
  7. <script>
  8. // 1.导入 eventBus.js 模块
  9. import bus from './eventBus'
  10. export default{
  11. data(){
  12. return {
  13. // 兄弟组件要传送的数据
  14. str:'我想对你说:hello world'
  15. }
  16. },
  17. methods:{
  18. send(){
  19. // 2.通过eventBus来发送数据
  20. bus.$emit('share',this.str)
  21. }
  22. }
  23. }
  24. </script>
  25. <style lang="less" scoped>
  26. h3{
  27. color: #f00;
  28. }
  29. .left-container{
  30. padding: 0 20px 20px;
  31. background-color: orange;
  32. min-height: 250px;
  33. flex: 1;
  34. }
  35. ::v-deep h5{
  36. color:#00f
  37. }
  38. </style>

3)在数据接受方,调用bus.$on('事件名称',事件处理函数)方法注册一个自定义事件

  1. <template>
  2. <div class="right-container">
  3. <h3>Right组件</h3>
  4. {{msgFromLeft}}
  5. </div>
  6. </template>
  7. <script>
  8. // 1.导入 eventBus.js 模块
  9. import bus from './eventBus'
  10. export default{
  11. data(){
  12. return {
  13. // 兄弟组件要接受的数据
  14. msgFromLeft:""
  15. }
  16. },
  17. created(){
  18. bus.$on('share',val=>{
  19. this.msgFromLeft = val
  20. // console.log('在Right组件中定义的share被触发了!',val);
  21. })
  22. }
  23. }
  24. </script>
  25. <style>
  26. .right-container{
  27. padding: 0 20px 20px;
  28. background-color: orange;
  29. min-height: 250px;
  30. flex: 1;
  31. }
  32. </style>

网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发