vuex用來管理vue的所有組件狀態。
首先下載vuex,”vuex”:”^3.0.1”,運用”vuex-persistedstate”來對資料進行緩衝。下載”vuex-persistedstate”
在檔案中引入:(建立一個store檔案夾,在檔案夾下的index.js檔案進行如下編寫)
import Vue from 'vue'import Vuex from 'vuex'import createPersistedState from 'vuex-persistedstate'Vue.use(Vuex)
定義簡單模組:
const module = { state: { user: { name: 'rookie' } }, getters: {}, mutations: { setUser(state, payload){ if(payload.hasOwnProperty('name')){ state.user.name = payload.name } } }, plugins: [createPersistedState()]}
上面是一個簡單的vuex,在vuex中對應的store應用,在store中包含組件的共用狀態state和改變狀態的方法(暫且稱作方法)mutations。注意state相當於對外的唯讀狀態,不能通過store.state.user.name來更改,使用store.commit方法通過觸發mutations改變state。
在頁面中擷取記錄的值name為rookie:
mounted(){ console.log(this.$store.state.user.name);}
store.state為擷取store中的值,此時在my頁面中列印出來的值為rookie,而我們想要修改name的值,則需要藉助store.commit方法來觸發mutations:
this.$store.commit('setUser',{name: 'kuke_kuke'})
在mutations中找到setUser,第二個參數payload為傳入的對象{name: ‘kuke_kuke’},調用方法hadOwnProperty來判斷傳入的對象是否有name屬性,從而修改state中的值,此時在頁面中再次列印user.name的值為’kuke _ kuke’。
最後匯出模組:
const store = new Vuex.Store(module)export default store
別忘記在main.js中擷取模組並使用:
import store from './store'new Vue({ store})
作者:rookie.he(kuke_kuke)
部落格連結:http://blog.csdn.net/qq_33599109
歡迎關注支援,謝謝。