加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

8种vue组件通信方式详细解析实例

发布时间:2019-04-10 21:32:09 所属栏目:建站 来源:web秀
导读:对于vue来说,组件是非常常见的,有很多平台都封装了了属于自己一套的组件,如element ui、we ui等等。同时组件之间的消息传递也是非常重要的,下面是我对组件之间消息传递的各种方式的总结,共有8种方式。如有不足之处,可以留言补充,互相学习。 1. prop

这种情况下可以使用中央事件总线的方式。新建一个Vue事件bus对象,然后通过bus.$emit触发事件,bus.$on监听触发的事件。

  1. Vue.component('brother1',{ 
  2.  data(){ 
  3.  return { 
  4.  myMessage:'Hello brother1' 
  5.  } 
  6.  }, 
  7.  template:` 
  8.  <div> 
  9.  <p>this is brother1 compoent!</p> 
  10.  <input type="text" v-model="myMessage" @input="passData(myMessage)"> 
  11.  </div> 
  12.  `, 
  13.  methods:{ 
  14.  passData(val){ 
  15.  //触发全局事件globalEvent 
  16.  bus.$emit('globalEvent',val) 
  17.  } 
  18.  } 
  19. }) 
  20. Vue.component('brother2',{ 
  21.  template:` 
  22.  <div> 
  23.  <p>this is brother2 compoent!</p> 
  24.  <p>brother1传递过来的数据:{{brothermessage}}</p> 
  25.  </div> 
  26.  `, 
  27.  data(){ 
  28.  return { 
  29.  myMessage:'Hello brother2', 
  30.  brothermessage:'' 
  31.  } 
  32.  }, 
  33.  mounted(){ 
  34.  //绑定全局事件globalEvent 
  35.  bus.$on('globalEvent',(val)=>{ 
  36.  this.brothermessage=val; 
  37.  }) 
  38.  } 
  39. }) 
  40. //中央事件总线 
  41. var bus=new Vue(); 
  42. var app=new Vue({ 
  43.  el:'#app', 
  44.  template:` 
  45.  <div> 
  46.  <brother1></brother1> 
  47.  <brother2></brother2> 
  48.  </div> 
  49.  ` 
  50. }) 

6. parent和children

  1. Vue.component('child',{ 
  2.     props:{ 
  3.       value:String, //v-model会自动传递一个字段为value的prop属性 
  4.     }, 
  5.     data(){ 
  6.       return { 
  7.         mymessage:this.value 
  8.       } 
  9.     }, 
  10.     methods:{ 
  11.       changeValue(){ 
  12.         this.$parent.message = this.mymessage;//通过如此调用可以改变父组件的值 
  13.       } 
  14.     }, 
  15.     template:` 
  16.       <div> 
  17.         <input type="text" v-model="mymessage" @change="changeValue"> 
  18.       </div> 
  19.   }) 
  20.   Vue.component('parent',{ 
  21.     template:` 
  22.       <div> 
  23.         <p>this is parent compoent!</p> 
  24.         <button @click="changeChildValue">test</button > 
  25.         <child></child> 
  26.       </div> 
  27.     `, 
  28.     methods:{ 
  29.       changeChildValue(){ 
  30.         this.$children[0].mymessage = 'hello'; 
  31.       }//在此我向大家推荐一个前端全栈开发交流圈:619586920 突破技术瓶颈,提升思维能力 
  32.     }, 
  33.     data(){ 
  34.       return { 
  35.         message:'hello' 
  36.       } 
  37.     } 
  38.   }) 
  39.   var app=new Vue({ 
  40.     el:'#app', 
  41.     template:` 
  42.       <div> 
  43.         <parent></parent> 
  44.       </div> 
  45.     ` 
  46.   }) 

7. boradcast和dispatch

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读