vue dispatch用法_Vuex基本用法
所謂的Vuex其實就是一個為Vue.js設計的數據倉庫,就是把各個組件公用的數據放到一個倉庫里面進行統一的管理
Vuex好處:
- 既使非父子組件間的數據共享也能變得簡單明了
- 讓程序變得更加可維護(將數據抽離了出來)
- 只要倉庫里面的數據發生了變化,在其他組件里面數據被引用的地方也會自動更新
Vuex怎么用?
先用vue-cli安裝項目框架
@vue/cli用法
yarn global add @vue/cli
NPM
npm install -g @vue/cli
安裝Vuex
Yarn
yarn add vuex
NPM
npm install vuex --save
初始化store.js
一般放到src/store/store.js下面
-
import Vue from "vue";
-
import Vuex from "vuex";
-
-
Vue.use(Vuex)
-
-
const store = new Vuex.Store({
-
state: {
-
test:'x'
-
},
-
mutations: {
-
changetest(state, xxx) {
-
state. test= xxx
-
}
-
},
-
actions:{
-
changetest(context, xxx) {
-
context. commit('changetest',xxx)
-
}
-
},
-
getters: {
-
test2: state => state.test
-
}
-
})
-
export default store;
state:相當於Vue的data
mutations:類似於事件,每個 mutation 都有一個字符串的事件類型 (type)和 一個回調函數 (handler)。這個回調函數就是我們實際進行狀態更改的地方,並且它會接受 state 作為第一個參數
actions: Action 類似於 mutation,不同在於Action 提交的是 mutation,而不是直接變更狀態,Action 可以包含任意異步操作
getters:可以認為是 store 的計算屬性,就像計算屬性一樣,getter 的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變才會被重新計算,接受 state 作為其第一個參數
好了,就這么簡單可以用了
使用Vuex
打開main.js,導入,然后用
-
import Vue from "vue";
-
import App from "./App.vue";
-
import store from "./store";
-
-
new Vue({
-
store,
-
render: h => h(App)
-
}).$mount( "#app");
好了你可以在所有App所有子組件里面使用Vuex了
如何使用 state
子組件能通過 this.$store 訪問到
-
this.$store.state.test
-
// x
如何使用 mutations
子組件能通過 this.$store.commit 訪問到
this.$store.commit('changetest',xxx)
它會去把 changetest 提交到 mutation 執行 ,第二個是載荷(可以理解為參數),大多數載荷應該是一個對象,這樣可以包含多個字段並且記錄的 mutation 會更易讀
如何使用 actions
子組件能通過 this.$store.dispatch 訪問到
this.$store.dispatch('changetest'xxx)
它會去把 changetest 分發到 actions 在通過 actions 提交到 mutation 執行
如何使用 getters
子組件能通過 this.$store.getters 訪問到
-
this.$store.getters.test2
-
//x
這些是簡單的使用教程,更多使用方法參考官方文檔
