簡潔易懂的vuex總結
1 下載vuex。
使用npm安裝 vuex。在控制命令列中輸入下邊的命令。
npm install vuex --save
2 引用vuex。
在專案的src下新建資料夾store。在store資料夾下新建index.js(或者叫做store.js)。在index.js裡面寫入程式碼:
// store.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state:{ }, getters:{ }, mutations:{ }, actions:{ } })
在main.js 中引入新建的vuex檔案,並掛載根vue例項上,這樣我們就可以使用vuex了。
// main.js
import store from './store/store.js'
new Vue({
el: '#app',
store, // 把 store 掛載vue例項上,這可以把 store 的例項注入所有的子元件
render: h => h(App)
})
3 state的使用。
我們在state物件中儲存很多變數,這也就相當於我們的資料庫。在元件中我們用 $store.state.aaa 獲取state中的變數。
// store.js state:{ aaa:"我儲存的變數" }, // myComponent.vue computed:{ getAaa(){ return this.$store.state.aaa; } }, methods: { getAaa(){ return this.$store.state.aaa; } }
mapState輔助函式。
mapState會更方便我們使用,首先我們需要在元件中引入mapState。然後在methods或者computed中使用...mapState()。
這樣我們在模板中可以直接使用 例如:{{aaa}}。
// myComponent.vue
import store from '../store/store'
import { mapState} from 'vuex'
computed: {
...mapState(['aaa'])
}
4 getters的使用。
getter是用來獲取state裡面的變數,並且在輸出之前對state裡面的變數進行加工修改。也可以看做輸出前攔截器。
// store.js
getters:{
getAaa:state=>state.aaa,
// getters也可使用它自己的屬性
add: (state, getters) => {
return getters.doneTodos++
}
},
// myComponent.vue
computed:{
getAaa(){
return this.$store.getters.getAaa
},
add(){
return this.$store.getters.add
}
},
getters的第一個引數預設是state。就是我們store裡面的state。它還接受getters作為第二個引數,就是我們store裡面的getters。
mapGetters的使用方法也很簡單,首先引入mapGetters,然後在methods或者computed中使用...mapGetters()。
// myComponent.vue
import { mapGetters } from 'vuex'
computed :{
...mapGetters(["getAaa","add"])
}
5 mutations的使用。
mutation是唯一可以更改 Vuex 的 store 中的狀態的唯一方法。在元件中 $store.commit( ) 方法向vuex提交我們的修改。
// store.js
mutations: {
add(state, n) {
state.aaa += n
}
}
// myComponent.vue
<button @click="$store.commit('add',10)">+</button>
當然它也有mapMutations輔助函式。
// myComponent
import {mapMutations } from 'vuex'
methods:{
...mapMutations(['add'])
}
5 actions的使用。
actions和之前講的mtations功能基本一樣,不同點是,actions是非同步的改變state狀態,而mutations是同步改變狀態。actions是可以呼叫mutations裡的方法。
- context:上下文物件,與 store 例項具有相同方法和屬性。
- {commit}:直接把commit物件傳遞過來,可以直接當commit使用。
// store.js
mutations: {
add (state) {
state.aaa++
},
reduce (state) {
state.aaa--
}
},
actions ={
addAction(context){
context.commit('add',10)
},
reduceAction({commit}){
commit('reduce')
}
}
mapActions的使用。
// myComponent
import {mapMutations } from 'vuex'
methods:{
...mapActions(['addAction','reduceAction'])
}
6 module模組組的使用。
當專案比較複雜,應用的資料比較多時。我們可以使用Vuex的module ,將 store 分割成模組(module)。每個模組擁有自己的 state、mutation、action、getter、甚至是巢狀子模組。
// store.js
const moduleA={
state,mutations,getters,actions
}
const moduleB={
state,mutations,getters,actions
}
export default new Vuex.Store({
modules:{
a:moduleA,
b:moduleB
}
})