H女王范儿 2019-12-23
网上有关vuex的文章很多,我这里只讲实用的:
//下面是一个js文件,用最简单最全的例子展示了全局数据 city 和 cityID 的声明以及改变的方法;
import Vue from ‘vue‘;
import Vuex from ‘vuex‘;
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
city: ‘深圳‘,
cityID: "1"
},
getters: {
getCity(state) { //方法名随意,主要是来承载变化的city的值,下面mutations,actions里面的方法名也是随意定的
return state.city
},
getCityId() { //方法名随意,主要是用来承载变化的cityID的值,下面mutations,actions里面的方法名也是随意的
return state.cityID
}
},
mutations: {
setCity(state, value) {
state.city = value;
},
setCityID(state, value) {
state.cityID = value;
}
},
actions: {
selectCity(context, params) {
context.commit(‘setCity‘, params.city);
},
selectCityID(context, params) {
context.commit(‘setCityID‘, params.id);
}
}
});
export default store;获取和修改state有使用辅助函数和不使用两种方法,如果使用,请在使用的文件中添加:
import {mapState,mapGetters,mapMutations,mapActions} from ‘vuex‘
1.不引入 mapState: this.$store.state2.引入 mapState:
computed: {
//设置别名,起到简化代码的作用,比如this.$store.state.cityID可以用this.cId替代
// 方法一:
// ...mapState({
// cId: state => state.cityID,
// cname:state => state.city
// }),
// 方法二:
// ...mapState({
// cId: ‘cityID‘,
// cname:‘city‘
// }),
// 方法三(不设置别名,直接使用this.cityID即可):
...mapState([‘cityID‘,‘city‘]),
},1.不引入 mapState:
方法一: 用this.$store.commit执行mutation里的方法 //this.$store.commit("setCityID", 6);
方法二: 用 this.$store.dispatch执行actions里的方法
//this.$store.dispatch("selectCity", { id: 6});2.引入 mapState(和获取state一样能设置别名,下面不配置别名):
methods: {
...mapActions([‘cityID‘,‘selectCityID‘]),
changeId(params) { //params为要修改的数,比如6
this.selectCityID({ id:params });
console.log(this.$store.state);//这时候打印出来cityID变为6了
}
},