Vuex4 匹配 Vue3;Vuex3 匹配 Vue2。
Vuex3 推荐搭配 Vue2 使用;Vuex4 推荐搭配 Vue2 和 Vue3 的 Options API 使用;Pinia 推荐搭配 Vue3 的 Composition API 使用。
Vuex 是一个专为 Vue 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
安装:
npm install vuex
。
创建并注册 Store 对象:
Vuex4 创建并注册 Store 对象。
// src/store/index.js
import { createStore } from "vuex"
// 1. 创建 Store 对象。Vuex 使用单一状态树,用一个对象就包含了全部的应用层级的状态,也就是说,整个应用中只会有一个 Store 对象
const store = createStore({ })
export default store
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
const app = createApp(App)
// 2. 注册 Store 对象
app.use(store)
app.mount('#app')
Vuex3 创建并注册 Store 对象。
// 1. 创建 Store 对象。Vuex 使用单一状态树,用一个对象就包含了全部的应用层级的状态,也就是说,整个应用中只会有一个 Store 对象
export default new Vuex.Store({})
import store from './store'
// 2. 注册 Store 对象
new Vue({
el: '#app',
store,
})
使用:
Vuex 有五个核心概念:state、getters、mutations、actions、modules。
在 state 中定义数据。
getters 类似于 computed 计算属性,可以对 state 中的数据进行处理。
提交 mutation 是 Vuex 中唯一可以修改状态的方式,但是只能进行同步操作。
如果想要进行异步操作,需要在 action 中,但是 action 中不能直接修改状态,最终还是需要通过提交 mutation 来修改。
modules 用来划分子模块。
state:
state:存储状态。mapState()
是其辅助函数。
state 的基本使用:
// src/store/index.js
import { createStore } from "vuex"
const store = createStore({
// 1. 使用 state 定义数据。Vuex 中的 state 状态是响应式的
state: () => ({
name: 'Lee',
})
})
export default store
// src/App.vue
<template>
<!-- 2. 在 template 模板中访问 state 中的数据 -->
<div>{
{ $store.state.name}}</div>
</template>
<script setup>
// 2. 在 Options API 中访问 state 中的数据
// console.log(this.$store.state.name)
// 2. 在 Composition API 中访问 state 中的数据。
// 如果对 state 中的数据进行赋值或者解构操作,赋值或者解构出来的数据不具有响应式。例如 appCount = store.state.count,appCount 不具有响应式
import { useStore } from 'vuex'
const store = useStore()
console.log(store.state.name)
</script>
<style scoped>
</style>
state 的映射使用:
当一个组件需要获取多个状态时,重复使用基本方法获取会有些冗余繁琐。可以通过 mapState()
辅助函数生成计算属性,将 state 中的数据映射到组件中。
在 Options API 中。
// src/App.vue
<template>
<div>{
{ name }}</div>
</template>
<script>
// 1. 导入 mapState 函数
import { mapState } from 'vuex'
export default {
computed: {
// 2. 使用 mapState 函数。mapState 函数返回一个对象,可以通过扩展运算符将它与自定义计算属性混合使用
...mapState(['name']),
}
}
</scr