cnpm i vuex axios -S 1 建立Vuex 倉庫 import Vue from 'vue' import Vuex from 'vuex' vue.use(Vuex) const store = new VueX.store({ state: {//存放狀態}, mutations:{//惟一修改狀態的地方,不在這裏作邏輯處理} }) export default store 2 在入口文件main.js下引入store import store from './store/index.js' 將store 放到根實例裏 以供全局使用 new Vue({ el:'#app', store, components:{App}, template:<App/> }) 開始使用store(以home組件爲例)
Vuex的使用也是一種漸進式的,你能夠從最簡單的開始使用,根據經驗和技術的增長,再漸進加強對它的使用,若是按照級別算vuex的使用能夠從最基本的t1級別開始,先總結最基本的前三個版本,後續有時間再總結其餘的。vue
1. 在hoome/script.js中進行請求數據 import Vue from 'vue' import axios from 'axios' export default { mounted(){ axios.get('請求數據的接口') .then((res)=>{this.$store.commit('changeList',res.data)}) //changeList至關於調用了在store.mutations中定義的修改狀態的方法 //res.data 就是在改變狀態時要修改的數據,須要在這傳遞過去。 .catch((err)=>{console,log(err)}) } } 2. 在store/index.js中定義 import Vue from 'vue' import Vuex from 'vuex' vue.use(Vuex) const store = new VueX.store({ state: { //存放狀態 list: [ ] //存放一個空的數組 }, mutations:{ //惟一修改狀態的地方,不在這裏作邏輯處理 //定義一個修改list的方法 //state 指上面存放list的對象,data 爲在請求數據出傳過來請求到的數據 changeList (state,data) { state.list = data //將請求來的數據賦值給list } } }) export default store 3. 在home/index.vue中渲染 <template> //渲染數據的時候經過this.store.state.list直接從store中取數據 //還能夠從其餘組件經過這種方法去用這個數據無需從新獲取 <li v-for='item of this.store.state.list' :key='item.id'>{{item.name}}</li> </template> 注意點: ( 若是咱們在home組件中獲取的數據,能夠在其餘組件中使用,可是是當頁面刷新默認進入home頁,也就是至關於修改了數據,再點擊其餘頁面也能有數據。若是咱們在user組件中獲取的數據要在home組件中使用,當頁面刷新數據是不會顯示的,由於此時尚未觸發user組件中的更改數據的方法,因此數據爲空,當點擊user頁面時,就會有數據,這個時候再去點擊home頁面咱們就可以看到在home 組件中使用user組件中獲取的數據了。解決這種問題的辦法能夠將數據存到本地一份或者都在首頁進行請求數據 )
在頁面進行渲染的時候咱們須要經過this.store.state去拿數據,這樣的寫法太長並且不太好 用計算屬性結合mapState去解決這個問題 1 在home/script.js中進行操做 import Vue from 'vue' import mapState from 'vuex' import axios from 'axios' export default { computed:{ //mapState爲輔助函數 ...mapState(['list']) }, mounted(){ axios.get('請求數據的接口') .then((res)=>{this.$store.commit('changeList',res.data)}) .catch((err)=>{console,log(err)}) } } 2 在home/index.vue中渲染 <template> <li v-for='item of list' :key='item.id'>{{item.name}}</li> </template>
使用常量去代替事件類型(便於查看狀態,利於維護) 1 在store下建立mutation-type.js export const CHANGE_LIST = 'CHANGE_LIST' 2 在store/index.js引入mutation-type.js import Vue from 'vue' import Vuex from 'vuex' import {CHANGE_LIST } from‘./mutation-type.js’ vue.use(Vuex) const store = new VueX.store({ state: { list: [ ] //存放一個空的數組 }, mutations:{ //咱們可使用Es6風格的計算屬性命名功能來使用一個常量做爲函數名 [CHANGE_LIST] (state,data) { state.list = data //將請求來的數據賦值給list } } }) export default store 3 在home/script.js中進行引入 import Vue from 'vue' import mapState from 'vuex' import axios from 'axios' import {CHANGE_LIST} from ‘../../store/mutation-type.js’ export default { computed:{ //mapState爲輔助函數 ...mapState(['list']) }, mounted(){ axios.get('請求數據的接口') .then((res)=>{this.$store.commit(CHANGE_LIST,res.data)}) .catch((err)=>{console,log(err)}) } }