借鑒博客:
https://segmentfault.com/a/1190000011914191
https://www.cnblogs.com/mica/p/10757965.html
一、vuex介紹:
vuex:其實相當於一個存儲數據的容器
vuex有4個屬性:state、getters、actions、mutations
state: 作用:用來自定義一些變量
getters: 作用:里面寫用來獲取state里數據的方法
actions: 作用:里面寫api接口方法
mutations: 作用:用來觸發事件,(就是在這里面寫方法來使用getters屬性,從而操作state里面的數據)
vuex容器里所有的操作,都要通過mutations來操作。
二、項目中怎么使用vuex
1、創建一個store目錄,里面創建一個store.js文件,store.js里面的內容可以設計成這樣:
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); let store = new Vuex.Store({ // 1. state state:{ city:"城市名" }, // // 2. getters,與組件的computed類似,用來實時監聽state的最新變化 getters:{ // 參數列表state指的是state數據 getCityFn(state){ return state.city; } }, // 3. actions // 通常跟api接口打交道 actions:{ // 設置城市信息 // 參數列表:{commit, state} // state指的是state數據 // commit調用mutations的方法 // name就是調用此方法時要傳的參數 setCityName({commit,state}, name){ // 跟后台打交道 // 調用mutaions里面的方法 commit("setCity", name); } }, // 4. mutations mutations:{ // state指的是state的數據 // name傳遞過來的數據 setCity(state, name){ state.city = name;//將傳參設置給state的city } } }); export default store;
2、然后在main.js中引用封裝了vuex代碼的store.js文件
import store from './store/store.js'; //引入后就可以有組件頁面使用this.$store來調用vuex里面的方法了
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
3、然后隨便找個組件頁面,來調用vuex中的state屬性中的city變量數據:
<p>測試vuex:(把城市數據存入到vuex中)</p> <el-row> <h1>{{getCityName}}</h1> </el-row>
在js中的computed里面寫上getCityName方法,返回vuex中的state屬性中的city,看city的數據能不能出來
//computed方法用來偵聽屬性,與watch監聽差不多,但不同的是computed結果會緩存,調用里面的方法不用加(),直接寫方法名調用
computed:{
getCityName:function(){
return this.$store.getters.getCityFn; //從vuex里面拿state中的city變量數據
}
},
4、然后看頁面效果:
5、修改vuex存儲的city變量值:
this.$store.dispatch("setCityName", "北上廣深");
。