vuex官網的解釋是:Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式。它採用集中式存儲管理應用的全部組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。
下面介紹在vue腳手架中簡單應用vuex來實現組件之間傳遞數據,固然組件之間傳遞能夠使用emit,但頁面組件愈來愈多涉及到數據傳遞就愈來愈麻煩,vuex的便利性就體現出來。javascript
先上圖看看簡單的案例(沒寫樣式,將就看吧),主頁homepage組件點擊按鈕"獲取城市列表",跳轉到城市列表組件citylist,在列表中點擊對應的城市後,返回主頁並將數據傳遞給主頁顯示出來。html
一般設計store對象都包含4個屬性:state,getters,actions,mutations。
如何理解這4個屬性呢,從本身的話來理解:vuestate (相似存儲全局變量的數據)
getters (提供用來獲取state數據的方法)
actions (提供跟後臺接口打交道的方法,並調用mutations提供的方法)
mutations (提供存儲設置state數據的方法)且看官方的一個示例圖:
從上圖能夠很好看出這幾個屬性之間的調用關係(不過官方圖沒有畫出getters的使用)
能夠看出:java
- 組件Vue Component經過dispatch來調用actions提供的方法
- 而actions除了能夠和api打交道外,還能夠經過commit來調mutations提供的方法
- 最後mutaions將數據保存到state中
- 固然,Vue Components還以經過getters提供的方法獲取state中的數據
因此store.js的代碼能夠設計成:git
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); let store = new Vuex.Store({ // 1. state state:{ city:"城市名" }, // // 2. getters 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;
就能夠在組件使用this.$store來調用方法github
import store from './store/store.js';
組件頁面中的city數據經過this.$store.getters來獲取store.js所寫getters提供的getCityFn方法vuex
<template> <div class="home"> <h1>{{city}}</h1> <!-- 按鈕導航 --> <router-link tag='button' to="/citylist">獲取城市列表</router-link> </div> </template>
<script> export default { data () { return { } }, computed:{ city:function() { // 經過vuex的getters方法來獲取state裏面的數據 return this.$store.getters.getCityFn; } } } </script>
當點擊列表的時候,經過this.$store.dispatch來調用store.js中actions所提供的setCityName方法,並將城市名傳參過去shell
<template> <div class="city"> <ul> <li v-for="(item,index) in cityArr" @click="backFn(index)"> <h2>{{item}}</h2> </li> </ul> </div> </template>
<script> export default { name: 'HelloWorld', data () { return { cityArr:['北京','上海','廣州','深圳','茂名','張家界','清遠','汕頭','佛山'] } }, methods:{ backFn : function(index){ // 調用vuex的ations設置城市的值 this.$store.dispatch("setCityName", this.cityArr[index]); //返回到首頁 this.$router.push("/"); } } } </script>
最後完成如開頭案例演示的效果
固然若是涉及大量數據,建議參考官方推薦的 目錄文件結構設計:
還有 官網案例
├── index.html ├── main.js ├── api │ └── ... # 抽取出API請求 ├── components │ ├── App.vue │ └── ... └── store ├── index.js # 咱們組裝模塊並導出 store 的地方 ├── actions.js # 根級別的 action ├── mutations.js # 根級別的 mutation └── modules ├── cart.js # 購物車模塊 └── products.js # 產品模塊
最後附上這個vuex簡單使用代碼 demo