vue——49-Vuex
阿新 • • 發佈:2018-11-10
官網:Vuex
Vuex 是為了儲存元件之間共享資料而誕生的,如果元件之間有要共享的資料,可以直接掛載到 Vuex 中,而不必通過父子元件之間傳值了,如果元件之間的資料不需要,這些不需要共享的私有資料,沒有必要放到 Vuex 中
注意:
- 只有共享的資料,才有權利放到 Vuex 中;
- 元件內部私有的資料,只要放到元件的 data 中即可;
- props 、 data 和 vuex 的區別:props 是父元件向子元件傳值;data 是元件內部私有資料;vuex 相當於一個全域性的共享資料儲存區域,就是一個公共資料倉庫
操作案例:
- 安裝:
cnpm i vuex -s
操作:
main.js
// 入口檔案
import Vue from 'vue';
// 配置 vuex 的步驟
// 2. 匯入包
import Vuex from 'vuex';
// 3. 註冊 vuex 到 vue 中
Vue.use(Vuex);
// 4. new Vue.Store() 例項,得到一個數據倉儲物件
let store = new Vuex.Store({
state: {
// 大家可以把 state 想象成元件中的 data ,專門用來儲存資料的
// 如果在元件中,想要訪問 store 中的資料,只能通過
// this.$store.state.*** 來訪問
count: 0
},
mutations: {
// 注意:如果要操作 store 中的 state 值,只能通過呼叫 mutation
// 提供的方法,才能操作對應的資料,不推薦直接操作 state 中的資料,
// 因為萬一導致了資料的紊亂,不能快速定位到錯誤的原因,因為每個組
// 件都可能有操作資料的方法;
increment(state) {
state.count++;
},
// 注意:如果元件想要呼叫 mutations 中的方法,
// 只能使用 this.$store.commit('方法名')
subtract(state, obj) {
// 注意:mutations 的函式引數列表中,最多支援兩個引數,其中,
// 引數1:是 state 狀態;引數2:通過 commit 提交過來的引數:
// 提交過來引數若是多個,可以以陣列物件的形式
state.count -= (obj.c + obj.d);
}
},
getters: {
// 注意:這裡的 getters ,只負責對外提供資料,不負責
// 修改資料,如果想要修改 state 中的資料,請去找 mutations
optCount: function (state) {
return '當前最新的 count 值是:' + state.count;
}
// getters 中的方法,和元件中的過濾器比較類似,因為過濾器和
// getters 都沒有修改原資料,都是把原資料做了一層包裝,提供給了呼叫者;
// 其次,getters 也和 computed 比較像,只要 state 中的資料發生了變化,
// 如果 getters 正好也引用了這個資料,那麼就會立即觸發 getters 的重新求值;
}
});
import App from './App.vue';
const vm = new Vue({
el: '#app',
render: c => c(App),
// 5. 將 vuex 建立的 store 掛載到 VM 例項上,只要掛在到了 VM 上
// 任何元件都能使用 store 來儲存資料
store
});
兩個元件:
amount.vue
<template>
<div>
<!--<h3>{{ '當前數量為:'+$store.state.count }}</h3>-->
<h3>{{ $store.getters.optCount }}</h3>
</div>
</template>
counter.vue
<template>
<div>
<input type="button" value="減少" @click="remove">
<input type="button" value="增加" @click="add">
<br>
<input type="text" v-model="$store.state.count">
</div>
</template>
<script>
export default {
data() {
return {
// count: 0
};
},
methods: {
add() {
// 雖然可以實現,但不要這麼用,後期維護困難
// 不符合 vuex 的設計理念
// this.$store.state.count++;
this.$store.commit('increment');
},
remove() {
this.$store.commit('subtract', {c: 3, d: 2});
}
}
};
</script>
總結:
- state 中的資料,不能直接修改,如果想要修改,必須通過 mutations
- 如果元件想要直接從 state 上獲取資料:需要 this.$store.state.***
- 如果元件,想要修改資料,必須使用 mutations 提供的方法,需要通過 this.$store.commit(‘方法的名稱’,唯一的一個引數)
- 如果 store 中 state 上的資料,在對外提供的時候,需要做一層包裝,那麼,推薦使用 getters,如果需要使用 getters,則用 this.$store.getters.***
附加:
- 應用場景:商城購物車的商品個數新增