Vue基礎4-組件及refs用法


組件

  組件是可復用的 Vue 實例,且帶有一個名字,我們可以在一個通過 new Vue 創建的 Vue 根實例中,把這個組件作為自定義元素來使用。組件將css、js、html封裝到一起。直接引用使用。

 

  全局組件

 1 <div id="app">
 2     <demo></demo>
 3     <demo></demo>
 4     <demo></demo>
 5 </div>
 6 
 7 //全局組件  8     Vue.component('demo',{  9         template:'<h1 @click="change">{{msg}}</h1>', 10         //組件中data必須是方法 return屬性值 11  data:function () { 12             return { 13                 msg:'msg'
14  } 15  }, 16  methods:{ 17  change:function () { 18                 this.msg = 'test'
19  } 20  } 21  }); 22  new Vue({ 23         el:'#app'
24     })

組件中的data屬性必須是一個函數,這樣可以根據作用域將每個組件的數據進行隔離,不會出現多組件復用,數據相同的問題。

組件中的props屬性可以接收組件在引用時傳遞的變量

組件中的template,模板屬性

父組件:vue實例化接管的div 就是父組件

子組件:在父組件即app 這個div標簽內部引用了全局組件中定義的組件,即為子組件

 

refs用法:通過給標簽定義ref屬性

 1 <div id="app">
 2     <div ref="test">ref=test</div>
 3     <input type="button" value="test" @click="change">
 4 </div>
 5 
 6 new Vue({  7         el:'#app',  8  data:{  9  }, 10  methods:{ 11  change:function () { 12                 this.$refs.innerText = '已被修改'
13  } 14  } 15     })

refs類似與dom操作的document.getElementByID的操作,可以獲取到元素的屬性(能獲取就能修改),但是由於Vue中都是對於data數據進行操作,一般用來和組件一起使用

運用的例子:兩個子組件和一個父組件,點擊子組件的數字,子組件數字自增1,點擊修改button實現點擊兩個子組件數字相加

 1 <div id="app">
 2     <test ref="a"></test>
 3     <test ref="b"></test>
 4     //父組件只能使用父組件的data.count屬性  5     <div>父組件--<span>{{count}}</span></div>
 6     <input type="button"  value="test" @click="change">
 7 </div>
 8 
 9 //全局組件 10     Vue.component('test',{ 11         template:'<div>子組件--<span @click="add">{{number}}</span></div>', 12  data:function () { 13             return{ 14  number:0 15  } 16  }, 17  methods:{ 18  add:function () { 19                 this.number++
20  } 21  } 22  }); 23  new Vue({ 24         el:'#app', 25  data:{ 26  count:0 27  }, 28  methods:{ 29  change:function () { 30                 this.count = this.$refs.a.number +this.$refs.b.number; 31  } 32  } 33     })

 

父子組件交互(子組件觸發父組件)

  實現一個例子:兩個子組件一個父組件,點擊子組件數字,子組件數字自增1,子組件每次變化,父組件的數字都自動將兩個子組件數字相加,即子組件變化自動觸發父組件 

 1 <div id="app">
 2     <demo @xxxx="addCount"></demo>
 3     <demo @xxxx="addCount"></demo>
 4     <div>父組件--<span>{{count}}</span></div>
 5 </div>
 6 <script src="../js/vue.js"></script>
 7 <script>
 8     Vue.component('demo',{  9         template:'<div>子組件---<span @click="add">{{num}}</span></div>', 10  data:function () { 11             return{ 12  num:0 13  } 14  }, 15  methods:{ 16  add:function () { 17                 this.num++; 18                 //子組件向父組件觸發xxxx事件,且可以向父組件傳遞多個子組件參數 19                 this.$emit('xxxx',this.num) 20  } 21  } 22  }); 23  new Vue({ 24         el:'#app', 25  data:{ 26  count:0 27  }, 28  methods:{ 29  addCount:function (num) { 30                 this.count += num 31  } 32  } 33  }) 34 </script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM