返回
深入浅出渐进式 Vuex 教程
前端
2023-09-16 10:02:22
Vuex 渐进式教程
Vuex 是一个用于管理 Vue.js 应用程序状态的库。它使您能够以集中和可预测的方式存储和管理应用程序的数据。Vuex 具有许多优点,包括:
- 中央化状态管理: Vuex 将应用程序的状态存储在一个中心位置,便于访问和修改。
- 可预测的状态更新: Vuex 使用 mutations 来更新状态,mutations 是纯函数,这意味着它们不会产生副作用,并且总是返回相同的结果。
- 时间旅行调试: Vuex 允许您记录状态的更改,以便您可以回溯时间并查看应用程序在特定时刻的状态。
获取 store 中 state 的值
要获取 store 中 state 的值,您可以使用 $store.state
属性。例如:
const count = this.$store.state.count
这将把 count
state 的值存储在 count
变量中。
优化代码结构
当项目比较大的时候,数据繁琐,如果按照上述方法使用 Vuex,打开 main.js
时,您会看到场景非常混乱,各种数据繁杂在一起,不便于日后的维护。为了优化代码结构,您可以按照以下步骤操作:
- 将 store 中的数据按照不同的模块进行划分。
- 将每个模块的 mutations 和 actions 单独放在一个文件中。
- 将 store 中的 getters 单独放在一个文件中。
这样,您的代码结构将更加清晰,便于维护。
实际示例
以下是一个使用 Vuex 管理应用程序状态的实际示例:
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
},
getters: {
doubleCount: state => {
return state.count * 2
}
}
})
export default store
// 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.vue -->
<template>
<div>
<h1>Count: {{ count }}</h1>
<button @click="increment">Increment</button>
<button @click="incrementAsync">Increment Async</button>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
computed: {
...mapState(['count'])
},
methods: {
...mapActions(['increment', 'incrementAsync'])
}
}
</script>
这个示例演示了如何使用 Vuex 管理应用程序状态。您可以使用 $store.state.count
获取 count
state 的值,也可以使用 $store.commit('increment')
提交一个 mutation 来增加 count
的值。