🎉🎉全局组件通信
📌 $bus
main.js挂载:
new Vue({
el:'#app',
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus = this // 安装全局事件总线 $bus
}
})
A—>B组件通信:例:B触发A组件中的事件
A:
//监听getSome事件
mounted() {
this.$bus.$on('getSome',(data)=>{
console.log('A组件接收到的数据',data);
})
},
//解绑getSome事件
beforeDestroy() {
this.$bus.$off('getSome');
},
B:
this.$bus.$emit('getSome','我是B组件,向A组件发送点数据');
📌 $on
任意组件监听全局事件
A.vue
//beforeMount==>页面data数据已初始化完成,未挂载到页面上
beforeMount() {
this.globalEventBind();
},
methods:{
//全局事件绑定-->upData
globalEventBind() {
//解绑事件
this.$root.$off("upData");
this.$root.$on("upData", (data) => {
console.log(data);
});
},
}
//任意位置触发A组件中绑定的 upData事件
this.$root.$emit("upData", {
name: 'wg',
sex: 'man',
});
📌 Vuex
目录结构
app.js
const state = {
userId: 'dfges4fdsaf0', //用户id
}
const mutations = {
CHECK_SDID: (state, id) => {
state.userId= id
},
}
const actions = {}
export default {
namespaced: true,
state,
actions,
mutations
}
getters.js
const getters = {
id: state => state.app.id;
//若有多个模块,如
id2: state.app2.id
}
export default getters
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
app
},
getters
})
export default store
miain.js 挂载
import store from './store';
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
vue文件使用
import store from "../../../store";
import { mapGetters } from 'vuex';
computed: {
//实时响应vuex数据
...mapGetters([
'id',
]),
}
//或
computed: {
// 对属性重命名,使用 getId
...mapGetters("app", {getId: "id"});
}
//使用vuex里数据
//this.id即可
//或
let myid = store.getters["app/id"]
//调用vuex方法
store.commit("app/CHECK_SDID", '6799');