網上有關vuex的文章很多,但有些比較復雜,這篇文章能讓你快速使用vuex:
vuex 用處:管理全局狀態(類似全局變量,每個組件都能訪問到)
結構:
- state 存放狀態
- mutations state成員操作(修改state值唯一的方法)
- getters 加工state成員給外界
- actions 異步操作
- modules 模塊化狀態管理
vuex 用法:
1. 安裝:npm install vuex --save (安裝vuex保存到本地)
2. 創建js文件(見下圖,這里我隨意命名為store.js)
3.然后我們在main.js文件中:
3.1 引入文件(根據自己的路徑寫): import store from './store.js';
3.2 在vue實例全局引入store對象:new Vue({store})
以上步驟就完成了,接下來是具體使用方法
//下面是一個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.state
2.引入 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"]), // 方法四(通過mapGetters): ...mapGetters(["getCity",'getCityId']) }
修改state的方法:
1.mutations:
1: 用this.$store.commit執行mutation里的方法
this.$store.commit("setCityID",6);
2:使用輔助函數
methods:{
...mapMutations(['
setCity','setCityID']),
}
//通過this.setCity(6),this.selectCityID({id:6})調用
2.actions:
1: 用this.$store.dispatch執行actions里的方法
this.$store.dispatch("selectCityID",{id:6});
2:使用輔助函數
methods:{
...mapActions(['
selectCity','selectCityID']),
}
//通過this.setCity(6),this.selectCityID({id:6})調用