Vue组件之间的通信

Vue组件

Vue组件是可复用的Vue实例,因此其接受与 new Vue 相同的选项,如 data、computed、watch、methods 以及生命周期钩子等,只用像 el 这中根实例特有的选项,其不可使用。

Vue.Component('Link', {
    data(){
        return {
            href: 'https://vuex.vuejs.org/zh-cn/'
        };
    },
    template: 'Vuex'
})

// 组件使用
Link>

Tips
data必须是一个函数,每个组件实例都可以维护一份被返回对象的独立拷贝。

data(){
    return {
        href: 'https://vuex.vuejs.org/zh-cn/'
    };
}

Vue组件注册

  • 全局注册
    通过Vue.Component(componentName,options)进行全局组件注册
Vue.Component('button-count',{
    ...options
})
  • 局部注册
    通过components选项进行组件局部注册
import ButtonCount from 'ButtonCount';
new Vue({
    components: {
        ButtonCount
    }
})

Vue组件数据传递

  • 通过 prop 向子组件传递数据
    所有的prop都是父子组件之间形成一个单行向下的数据传递,即父组件的prop更新会向子组件传递,反之不行。
// parent