通过$on监听favorites事件,并定义事件的处理函数
this.$root.$on("favorites", list => {this.favorites = list});
通过$emit来发射favorites事件,且传递参数
this.$root.$emit("favorites", favorites);
通过$off来接触事件监听
this.$root.$off("favorites");
使用 :和 prop 来传递参数
父组件:通过:传值
子组件:通过prop订阅
export default {
name: "LobbyMain",
components: { GameItem },
props: ["games", "isMain"],
data() {
return {
favorites: [],
incTimerId: 0
};
},
filterGame() {
let vaildGame = Object.values(this.games).filter(
game =>
game.isactived == "1" &&
(!this.gameTypes.length || this.gameTypes.includes(game.lotterytype))
);
return vaildGame;
},
vuex主要使用的是四个模块:
State 单一状态树:记录vuex的存储的所有值
Getter 获取者:获取记录的值
Mutation 变化:只能通过Mutation来修改State上的值,但Mutation是同步方法
Action 动作: 可以通过Action出发Mutation修改值,且可以使用异步方法
例子:
/*
* @Author: tom
* @Date: 2019-10-30 16:37:20
* @LastEditor: tom
* @Version:
* @Description:
*/
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
latestTransId: '',
comm: 0,
types: [],
isSkipFavorite: false,
favorites: [],
gLocal:{}, //全局最后id
activeItemGroup:'all'
},
getters:{
isSkipFavorite:(state)=>{
let result = sessionStorage.getItem("isSkipFavorite")? sessionStorage.getItem("isSkipFavorite"): state.isSkipFavorite;
sessionStorage.removeItem("isSkipFavorite");
return result;
},
activeItemGroup:(state)=>{
return sessionStorage.getItem("activeItemGroup")?sessionStorage.getItem("activeItemGroup"):state.activeItemGroup;
},
types:(state)=>{
let result;
if(sessionStorage.getItem("types")){
result = sessionStorage.getItem("types").split(',');
result = result.map((item)=>Number(item));
}else{
result = state.type;
}
return result;
},
},
mutations:{
changeGLocal(state,payload){//改变全局最后id
Vue.set(state.gLocal, payload[0], payload[1]);
},
changeActiveItemGroup(state,payload){
sessionStorage.setItem('activeItemGroup',payload);
state.activeItemGroup = payload;
},
changeTypes(state,payload){
sessionStorage.setItem('types',payload);
state.types = payload;
}
},
actions:{
changeGLocal({ commit }, payload) {
commit('changeGLocal', payload);
},
changeActiveItemGroup({ commit }, payload) {
commit('changeActiveItemGroup', payload);
},
changeTypes({ commit }, payload) {
commit('changeTypes', payload);
}
}
})
Action通过commit出发Mutation的事件,而外部则通过dispach来调用Action中定义的方法间接操作Mutation。
//外部直接调用Mutation修改
this.$store.commit('increment');
// 外部调用Action
this.$store.dispatch("changeGLocal",glocalValue);
通过${}来插入变量