Vue组件通信

一、props和$emit(父子组件通信)








二、v-model(双向绑定)

遍历数组里面双向绑定必须使用 v-model="list[index]"








三、.sync语法糖(双向绑定)








四、$attrs、$props和$listeners(孙组件通信)、(provide、inject 子孙组件通信)













五、$root、$parent 和 $children(访问组件)

$root和$parent 都能够实现访问父组件的属性和方法,如果存在多级子组件,$root 访问得到的是根父组件,如果当前实例没有父实例,此实例将会是其自己。









六、EventBus(事件总线)

// EventBus
import Vue from 'vue'
const EventBus = new Vue();
export default EventBus












全局注册EventBus,在入口文件添加方法到Vue原型

const EventBus = new Vue();
Object.defineProperties(Vue.prototype, {
    $event: {
        get: function () {
            return EventBus
        }
    }
})
//发布
this.$event.$emit('event',datas);
//监听
this.$event.$on('event',($event) => { })

七、Vuex(状态管理)

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state={   //要设置的全局访问的state对象
     showFooter: true,
     changableNum:0
     //要设置的初始属性值
   };
const getters = {   //实时监听state值的变化(最新状态)
    isShow(state) {  //承载变化的showFooter的值
       return state.showFooter
    },
    getChangedNum(){  //承载变化的changebleNum的值
       return state.changableNum
    }
};
const mutations = {
    show(state) {   //自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);
        state.showFooter = true;
    },
    hide(state) {  //同上
        state.showFooter = false;
    },
    newNum(state,sum){ //同上,这里面的参数除了state之外还传了需要增加的值sum
       state.changableNum+=sum;
    }
};
 const actions = {
    hideFooter(context) {  //自定义触发mutations里函数的方法,context与store 实例具有相同方法和属性
        context.commit('hide');
    },
    showFooter(context) {  //同上注释
        context.commit('show');
    },
    getNewNum(context,num){   //同上注释,num为要变化的形参
        context.commit('newNum',num)
     }
};
  const store = new Vuex.Store({
       state,
       getters,
       mutations,
       actions
});
export default store;

你可能感兴趣的:(Vue组件通信)