Vuex是一個針對Vue.js開發的狀態管理模式。就是一個工具,管理(修改或設置)所有組件用到的數據,而不需要藉助event bus或props在組件間傳值。
vuex說明:
- 整個vuex的核心是一個Store,裏面包含有state,mutaions,actions,getters。
- state是數據存儲對象,需要存儲的數據都可以存儲在state中。
- mutations中存儲操作State中數據的方法,可以直接通過commit進行調用,但是這種調用發生時同步的。
- actions存儲了觸發mutations中的函數的方法,通過dispatch可以調用actions中的方法,它是異步調用法師。
使用vuex:
下載:
npm install vuex -S
定義一個vuex模塊
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {}
const mutations = {}
const actions = {}
const getters = {}
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
在main.js注入
// main.js
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(Counter)
})
例子:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 存儲數據的對象
const state = {
username: '',
current: {}
}
// 存儲着操作state數據的函數
const mutations = {
// state:可以理解爲state對象
setUsername: (state, value) => {
state.username = value
}
}
// 存儲着觸發mutations中的函數的方法
const actions = {
setUsernameAction: ({ commit }, value) => {
commit('setUsername', value)
}
}
// 訪問器
const getters = {
getUsername: (state) => {
return state.username + 'aa'
}
}
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
使用:
// 將數據存儲到vuex的state中
this.$store.state.username = res.data.data.username
// commit(mutations中的函數名稱):同步調用方式:不建議使用
this.$store.commit('setUsername', res.data.data.username)
// 以異步的方式進行數據的處理
this.$store.dispatch('setUsernameAction', res.data.data.username)