vue2.0 組件化及組件傳值



組件 (Component) 是 Vue.js 最強大的功能之一。組件可以擴展 HTML 元素,封裝可重用的代碼。在較高層面上,組件是自定義元素,Vue.js 的編譯器為它添加特殊功能。在有些情況下,組件也可以表現為用 is 特性進行了擴展的原生 HTML 元素。

組件A寫法:

   <template> <div class="componentA"> ... </div> </template> <script> export default { data () { return { msg: 'component-A', } } } </script> <style> </style>

組件B寫法:

   <template> <div class="message" id="componentB"> ... </div> </template> <script> import Vue from 'vue' export default Vue.component('my-component', { template: '#componentB ', data(){ return { msg: 'component-B', } } }) </script> <style> </style>

在父組件component
分別引用掛載

   <template> <div> <component-A></component-A> <component-B></component-B> </div> </template> <script> import componentA from './component-a.vue'; import componentB from './component-b.vue' export default { data () { return { } }, components:{ "component-A":componentA, "component-B":componentB } } </script> <style> </style>

10.2組件間傳值

對於簡單的父子組件或是同屬同一父組件的兄弟組件之間的通信,vue提供了方法,沒必要用到vuex

10.2.1 父組件向子組件傳值:

父組件:

<component-A :logo="logoMsg"></component-A> //logoMsg是父組件data里的值

子組件:

 <template> <div class="componentA"> <div>{{logo}}</div> </div> </template> ... data(){ } props:["logo"], ...

10.2.2子組件調用父組件方法並向父組件傳值:

父組件:

   
   <component-A :logo="logoMsg" @toParent="componenta"></component-A> ... methods:{ componenta:function(data){ //data就是子組件傳遞過來的值 this.data1 = data } }

子組件:

     methods:{ toParent:function(){ this.$emit('toParent',this.data1) //調用父組件toParent方法,並傳遞參數 } }

效果圖:

兄弟組件之間傳值:在B組件修改父組件數據時。選擇修改傳給A組件的數據即可。

效果圖:

10.2.3事件總線:不相關組件之間傳遞數據

bus.js文件:

   import Vue from 'vue' export default new Vue()

組件B $emit觸發事件:

  import Bus from './bus.js' ... byBus:function(){ Bus.$emit('byBus',this.byBusData) }

組件A $on接受事件傳遞數據

    ...
    data(){ }, created(){ Bus.$on('byBus',(data)=>{ this.busData = data }) },

效果圖:

 


免責聲明!

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



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