网上有关vuex的文章很多,我这里只讲实用的:
vuex 用处:管理全局状态(类似全局变量,每个组件都能访问到)
vuex用法:(下面是js文件,操作中以读取和修改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的值 return state.city }, getCityId() { //方法名随意,主要是用来承载变化的cityID的值 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); } } }); //上面用最简单最全的例子展示了全局数据 city和 cityID的声明以及改变的方法; //获取state的方法: this.$store.state //修改state的方法:1.用this.$store.commit执行mutation里的方法 2.用 this.$store.dispatch执行actions里的方法 // this.$store.commit("setCityID", 6); // this.$store.dispatch("selectCity", { id: 110 }); export default store;
- 获取state的方法:
1.不使用mapState: this.$store.state.cId
2.使用mapState: (下面有三种...mapSate,任何一种都可以)
computed: { //mapState其实就是设置别名,简化代码,比如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:
1.1用this.$store.commit执行mutation里的方法
//this.$store.commit("setCityID", 6); 1.2.用 this.$store.dispatch执行actions里的方法 //this.$store.dispatch("selectCity", { id: 6});2.使用mapState:
methods: { ...mapActions(['cityID','selectCityID']), changeId(params) { //params为要修改的数,比如6 this.selectCityID({ id:params }); console.log(this.$store.state);//这时候打印出来cityID变为6了 } },