特色: 1.Vuex 的狀態存儲是響應式的。當 Vue 組件從 store 中讀取狀態的時候,若 store 中的狀態發生變化,那麼相應的組件也會相應地獲得高效更新。vue
2.你不能直接改變 store 中的狀態。改變 store 中的狀態的惟一途徑就是顯式地提交 (commit) mutation。vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
userName: 'phoebe',
age: '23',
habit: 'dance'
},
//主要是爲了修改state
mutations: {
getUserName (state,value) {
state.userName = value
}
},
// action就是爲了提交mutation
actions: {
getUserName (context,value) {
context.commit('getUserName',value)
}
}
})
export default store
複製代碼
//store/index.js
state:{
userName: 'phoebe',
age: '23',
habit: 'dance'
}
// app.vue
// 1.簡單獲取
this.$store.state.age
this.$store.state.habit
this.$store.state.userName
//2.使用輔助函數 mapState
import { mapState } from 'vuex'
computed: {
//this.habit :dance 便可調用
...mapState(['habit','age'.'userName'])
},
複製代碼
// store/index.js
mutations: {
getUserName (state,value) {
state.userName = value
}
},
// app.vue
// 1.簡單commit
this.$store.commit('getUserName','phoebe')
// 2.使用輔助函數 mapMutations將組件中的 methods 映射爲 store.commit 調用
import {mapMutations} from 'vuex'
methods: {
...mapMutations(['getUserName']),
init () {
//this.$store.state.userName:'change phoebe to MM' 便可改變
this.getUserName('change phoebe to MM')
}
}
複製代碼
// store/index.js
mutations: {
getUserName (state,value) {
state.userName = value
}
},
// action就是爲了提交mutation
actions: {
getUserName (context,value) {
context.commit('getUserName',value)
}
}
// app.vue
//1. 簡單分發
this.$store.dispatch('getUserName', 'change name by action')
//2.使用 mapActions 輔助函數將組件的 methods 映射爲 store.dispatch 調用
import { mapActions} from 'vuex'
methods: {
...mapActions(['getUserName']),
}
init (){
//this.$store.state.userName:'change phoebe to MA' 便可改變
this.getUserName('change phoebe by MA')
}
複製代碼