欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue.js中兄弟組件之間互相傳值實例

 更新時間:2017年06月01日 15:38:56   作者:小碼過河找八哥  
本篇文章主要介紹了Vue.js中兄弟組件之間互相傳值實例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

兄弟組件之間互相傳值,需要建立一個“中轉(zhuǎn)站”(新的vue實例),并且需要主動觸發(fā)。

實例上的$on方法來接受監(jiān)聽。

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>組件傳值</title>
 <script src="vue.js"></script>
</head>
<body>
 <div id="box">
 <child1></child1>
 <child2></child2>
 </div>

 <template id="c1">
 <h1>~~~~~~我是哥哥~~~~{{msg}} <button @click='fn'>點擊</button></h1>
 </template>
 <template id="c2">
 <h3>~~~~~~我是弟弟~~~~{{msg2}}</h3>
 </template>
</body>
</html>
<script>
 var Hub=new Vue();  // 1) 中轉(zhuǎn)站,其中不需要設置任何參數(shù)

 var vm=new Vue({
 el: '#box',
 components:{
  child1:{
  template:'#c1',
  data:function(){
   return {
   msg: 'hello'
   }
  },
  methods:{
   fn:function(){
   // 2) 主動觸發(fā)監(jiān)聽(中轉(zhuǎn)站觸發(fā)監(jiān)聽)
   console.log(this.msg); //hello
   Hub.$emit('change',this.msg) //$emit觸發(fā)監(jiān)聽方法
   }
  }
  },
  child2:{
  template:'#c2',
  data:function(){
   return {
   msg2: 'world'
   }
  },
  // 創(chuàng)建完成  new Vue  create mount
  // 鉤子函數(shù)
  created(){
   // 3) 接收監(jiān)聽  $on('事件名稱',function(val){}) val是傳遞過來的值
   Hub.$on('change',function(val){
   console.log(val) //hello
   // this.msg2 = val;
   })
  }
  }
  
 }
 })
</script>

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論