Vue2從0到1(四):Vue組件化及組件間傳值

前面講了環境的搭建用webpack打包vueVue-router的使用以及vuex的使用

下面講一下Vue組件化及組件間傳值:

主要包括 父子組件間傳值,兄弟組件間傳值,不相關組件間傳值。

10.Vue組件化及組件間傳值

10.1 Vue組件化

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

組件A寫法:webpack

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

組件B寫法:git

<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
分別引用掛載github

<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提供了方法,不必用到vuexweb

10.2.1 父組件向子組件傳值:

父組件:vuex

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

子組件:segmentfault

<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
         }
     }

子組件:this

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

效果圖:
圖片描述spa

兄弟組件之間傳值:在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
       })
    },

效果圖:圖片描述

更復雜的數據傳遞就要用到vuex

代碼託管於github 歡迎star

相關文章
相關標籤/搜索