| 
                         这种情况下可以使用中央事件总线的方式。新建一个Vue事件bus对象,然后通过bus.$emit触发事件,bus.$on监听触发的事件。 
- Vue.component('brother1',{ 
 -  data(){ 
 -  return { 
 -  myMessage:'Hello brother1' 
 -  } 
 -  }, 
 -  template:` 
 -  <div> 
 -  <p>this is brother1 compoent!</p> 
 -  <input type="text" v-model="myMessage" @input="passData(myMessage)"> 
 -  </div> 
 -  `, 
 -  methods:{ 
 -  passData(val){ 
 -  //触发全局事件globalEvent 
 -  bus.$emit('globalEvent',val) 
 -  } 
 -  } 
 - }) 
 - Vue.component('brother2',{ 
 -  template:` 
 -  <div> 
 -  <p>this is brother2 compoent!</p> 
 -  <p>brother1传递过来的数据:{{brothermessage}}</p> 
 -  </div> 
 -  `, 
 -  data(){ 
 -  return { 
 -  myMessage:'Hello brother2', 
 -  brothermessage:'' 
 -  } 
 -  }, 
 -  mounted(){ 
 -  //绑定全局事件globalEvent 
 -  bus.$on('globalEvent',(val)=>{ 
 -  this.brothermessage=val; 
 -  }) 
 -  } 
 - }) 
 - //中央事件总线 
 - var bus=new Vue(); 
 - var app=new Vue({ 
 -  el:'#app', 
 -  template:` 
 -  <div> 
 -  <brother1></brother1> 
 -  <brother2></brother2> 
 -  </div> 
 -  ` 
 - }) 
 
  
6. parent和children 
- Vue.component('child',{ 
 -     props:{ 
 -       value:String, //v-model会自动传递一个字段为value的prop属性 
 -     }, 
 -     data(){ 
 -       return { 
 -         mymessage:this.value 
 -       } 
 -     }, 
 -     methods:{ 
 -       changeValue(){ 
 -         this.$parent.message = this.mymessage;//通过如此调用可以改变父组件的值 
 -       } 
 -     }, 
 -     template:` 
 -       <div> 
 -         <input type="text" v-model="mymessage" @change="changeValue"> 
 -       </div> 
 -   }) 
 -   Vue.component('parent',{ 
 -     template:` 
 -       <div> 
 -         <p>this is parent compoent!</p> 
 -         <button @click="changeChildValue">test</button > 
 -         <child></child> 
 -       </div> 
 -     `, 
 -     methods:{ 
 -       changeChildValue(){ 
 -         this.$children[0].mymessage = 'hello'; 
 -       }//在此我向大家推荐一个前端全栈开发交流圈:619586920 突破技术瓶颈,提升思维能力 
 -     }, 
 -     data(){ 
 -       return { 
 -         message:'hello' 
 -       } 
 -     } 
 -   }) 
 -   var app=new Vue({ 
 -     el:'#app', 
 -     template:` 
 -       <div> 
 -         <parent></parent> 
 -       </div> 
 -     ` 
 -   }) 
 
  
7. boradcast和dispatch                         (编辑:我爱故事小小网_铜陵站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |