VueX
Vuex 是 Vue 狀態管理模式的框架。其最大的特點就是響應式數據數據存儲。
簡單來說,就是 vuex 在自己的核心 store 中存儲數據,這些數據一旦發生變化,相應的所有使用到該數據的組件都會高效的更新。
並且 Vuex 的 store 中的數據,是全局對象,在所有的組件中都可以直接調用,而不需要普通組件的 props 和 emit 等操作。
VueX 安裝
npm i -D vuex
VueX 使用
main.js 中導入 vuex 並配置
// 導入 Vue 框架
import Vue from "vue";
// 導入 Vuex 組件
import Vuex from 'vuex';
//使用 vuex 組件
Vue.use(Vuex);
/**
* vuex 的配置
* store 包含了應用的數據狀態和操作過程。
* Vuex 裏的數據都是響應式的,任何組件使用同一 store 的數據時,只要 store 變化,對應的組件也會立即更新
*/
const store = new Vuex.Store({
/**
* 數據保存在 Vuex 的 state 字段中。
* state 中的數據只能讀取,不能手動改變。改變 state 中的數據唯一的途徑就是顯示的提交 mutations
* 比如實現一個計數器
* 在任何組件中,都可以通過 $store.state.count 讀取
*/
state: {
count: 0,
list: [1, 12, 23, 34, 45, 56, 67, 78, 89, 90]
},
/**
* mutations 用來直接修改 state 中的數據
* 在組件中,通過 this.$store.commit 方法來執行 mutations
* 比如:this.$store.commit('increment')
* mutations 的第二個參數,可以是數字、字符或對象。
* 比如:decrease(state, n = 3) //這種設置默認值的語法時 ES6 的
*
* mutation 中儘量避免異步操作
* 因爲異步操作,組件在 commit 之後無法做到立即更新
*/
mutations: {
increment(state) {
state.count++;
},
decrease(state, n = 3) {
state.count -= 3;
},
pushRandom(state) {
state.list.push(Math.random().toFixed(2) * 100);
}
},
/**
* getters 方法
* getters 方法在這裏的作用類似於計算屬性
* getters 方法也可以依賴其他的 getter 方法,把 getter 作爲第二個參數
*/
getters: {
filteredList: state => {
return state.list.filter(item => item % 2 == 0);
},
listCount: (state, getters) => {
return getters.filteredList.length;
}
},
/**
* actions 和 mutations 類似。不同的是 action 裏面提交可以進行異步操作業務邏輯
* actions 通過 commit 方法提交方法,然後組件通過 $store.dispatch 觸發(使用方法類似於子組件 $emit 傳值 父組件on 監聽)
*/
actions: {
pushRandom(context) {
context.commit('pushRandom');
}
}
})
// 創建 vue 實例
new Vue({
el: "#app",
//使用vuex
store: store,
});
任意組件中都可以使用 vuex 的數據
<template>
<div>
<h1>VueX調用實例</h1>
<p>{{$store.state.count}}</p>
<p>{{count}}</p>
<button @click="handleIncrement">+1</button>
<button @click="handleDecrease">-3</button>
<hr>
<div>原數組:{{list}}</div>
<div>數組:{{filteredList}}</div>
<div>長度:{{listCount}}</div>
<button @click="handlePushRandom">push random</button>
</div>
</template>
<script>
export default {
computed: {
//訪問 Vuex 中的屬性,可以直接寫在 template 中,也可以通過計算屬性來顯示
count() {
return this.$store.state.count;
},
list() {
return this.$store.state.list;
},
filteredList() {
return this.$store.getters.filteredList;
},
listCount() {
return this.$store.getters.listCount;
}
},
methods: {
handleIncrement() {
this.$store.commit("increment");
},
handleDecrease() {
this.$store.commit("decrease");
},
handlePushRandom() {
this.$store.dispatch("pushRandom");
}
}
};
</script>