vuex 快速上手,具体使用方法总结(含使用例子)
网上有关vuex的文章很多,我这里只讲实用的:
vuex 用处:管理全局状态(类似全局变量,每个组件都能访问到)
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‘
用到里面哪个就引入哪个,如果不使用则不需要添加。
获取state的方法:
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‘]),
},修改state的方法:
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了
}
},相关推荐
CSCCockroach 2020-09-15
lbPro0 2020-07-05
MrSunOcean 2020-06-21
lylwanan 2020-06-14
Callmesmallpure 2020-05-31
ShaLiWa 2020-05-25
墨龙吟 2020-04-24
MrSunOcean 2020-04-24
H女王范儿 2020-04-22
lbPro0 2020-04-16
ShaLiWa 2020-02-29
ShaLiWa 2020-01-17
MrSunOcean 2020-01-03
lbPro0 2020-01-01
H女王范儿 2019-12-29