Vuex
安装Vuex
npm install vuex
store
每一个Vue应用的核心就是store(仓库)
- store本质上是一个容器 它包含着你的应用中大部分的状态(state)
Vuex和单纯的对象有什么区别
第一: Vuex的状态存储是响应式的 - 当Vue组件从store中读取状态的时候 若store中的状态发生变化 那么相应的组件也会被更新
第二:你不能直接改变store中的状态 - 改变store中的状态的唯一途径就是显示提交(commit) mutation
- 这样使得我们可以方便的跟踪每一个状态的变化 从而让我们能够通过一些工具帮助我们更好的管理应用的状态
使用步骤 - 创建store对象
- 在app中通过插件安装
useStore
在 setup 钩子函数中调用该方法可以获取注入的 store。当使用组合式 API 时,可以通过调用该方法检索 store。
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
}
}
组件中使用store
在组件中使用store 我们按照如下方式
- 在模板中使用
- 在options api中使用 比如computed
- setup中使用
创建一个保存计算属性的store
const counter = {
namespaced: true, //该模块称为命名空间模块
store: () => {
return: {
count: 99
}
},
mutations: {
incrementCount(state) {
console.log(state)
state.count++
}
},
getters: {
doubleCount(state, getters, rootState) {
return state.count + rootState.tootCounter
}
},
actions: {
incrementCountAction(context) {
context.commit("incrementCount")
}
}
}
export defaut cunter
单一状态树
Vuex使用单一状态树
- 用一个对象个就包含了全部的应用层级的状态
- 采用的是SSOT, Single Source of Truth, 也可以翻译成单一数据源
这也意味着 每个应用将仅仅包含一个store实例 - 单状态树和模块化并不冲突
单一状态树的优势 - 如果你的状态信息是保存到多个Store对象中的 那么之后的管理与维护等等会变的特别困难
- 所以Vuex也使用了单一状态树来管理应用层级的全部状态
- 单一状态数能够让我们最直接的方式找到某个状态的片段
- 而且在之后的维护和调试过程中 也可以非常方便的管理与维护
组件获取状态
在vue组件中获取上述定义命名空间的counter
<template>
<div class="home">
<h2>Home Page</h2>
<!-- 1.使用state时, 是需要state.moduleName.xxx -->
<h2>Counter模块的counter: {{ $store.state.counter.count }}</h2>
<!-- 2.使用getters时, 是直接getters.xxx -->
<h2>Counter模块的doubleCounter: {{ $store.getters["counter/doubleCount"] }}</h2>
<button @click="incrementCount">count模块+1</button>
</div>
</template>
<script setup>
import { useStore } from 'vuex'
// 告诉Vuex发起网络请求
const store = useStore()
// 派发事件时, 默认也是不需要跟模块名称
// 提交mutation时, 默认也是不需要跟模块名称
function incrementCount() {
store.dispatch("counter/incrementCountAction")
}
</script>
<style scoped>
</style>
如果我们有很多个状态都需要获取话,可以使用mapState的辅助函数:
- mapState的方式一:对象类型;
- mapState的方式二:数组类型;
- 也可以使用展开运算符和来原有的computed混合在一起;
在optionsAPI中使用mapState
当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
computed: mapState([
// 映射 this.count 为 store.state.count
'count'
])
mapState 函数返回的是一个对象。我们如何将它与局部计算属性混合使用呢?通常,我们需要使用一个工具函数将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性。但是自从有了对象展开运算符,我们可以极大地简化写法
computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}
在setup中使用mapState
在setup中如果我们单个获取状态是非常简单的
- 通过useState拿到sotre后去获取某个状态即可
- 但是如果我们需要使用mapState功能?
默认情况下,Vuex并没有提供非常方便的使用mapState的方式,这里我们进行了一个函数的封装:
import {useStore, mapState} from 'vuex'
import { computed } from 'vue'
export default function useState(mapper) {
const store = useStore()
const stateFnsObj = mapState(mapper)
const newState = {}
Object.keys(stateFnsObj).forEach(key => {
newState[key] = computed(stateFnsObj[key].bind({ $store: store }))
})
return newState
}
<script setup>
import useState from "../hooks/useState"
const { name, level } = useState(["name", "level"])
</script>
}
gettters的基本使用
当某些属性我们可能需要经过变化后来使用 这个时候可以使用getters
const store = createStore({
state() {
return {
books: [
{name: 'vuejs', count: 2, price: 110},
{name: 'react', count: 3, price: 120}
]
}
},
getters: {
totalPrice(state) {
let totalPrice = 0
for(const book of state.books){
totalPrice += book.count + book.price
}
return totalPrice
}
}
})
getters第二个参数
getters: {
totalPrice(state, getters) {
let totalPrice = 0
for(const book of state.books){
totalPrice += book.count + book.price
}
return totalPrice + ", " + getters.myName
},
myName(state) {
return state.name
}
}
getters的返回函数
getters中的函数本身 可以返回一个函数 那么在使用的地方相当于可以调用这个函数
getters: {
//getters是可以返回一个函数的, 调用这个函数可以传入参数
getFriendById(state) {
return function(id) {
const friend = state.friends.find(item => item.id === id)
return friend
}
}
}
<template>
<div class="app">
<!-- <button @click="incrementLevel">修改level</button> -->
<h2>doubleCounter: {{ $store.getters.doubleCounter }}</h2>
<h2>friendsTotalAge: {{ $store.getters.totalAge }}</h2>
<h2>message: {{ $store.getters.message }}</h2>
<!-- 根据id获取某一个朋友的信息 -->
<h2>id-111的朋友信息: {{ $store.getters.getFriendById(111) }}</h2>
<h2>id-112的朋友信息: {{ $store.getters.getFriendById(112) }}</h2>
</div>
</template>
<script>
export default {
computed: {
}
}
</script>
<script setup>
</script>
<style scoped>
</style>
mapGetters的辅助函数
computed: {
...mapGetters(['totalPrice', 'myName']),
...mapGetters({
finalPrice: 'totalPrice',
finalName: 'myName'
})
}
Mutation基本使用
更改Vuex的Store中的状态的唯一方式是提交mutation
mutations: {
increment(state) {
state.counter++
},
decrement(state) {
state.counter--
}
}
Mutation携带数据
很多时候我们在提交mutation的时候 会携带一些数据 这个时候我们可以使用参数
mutations: {
addNumber(state, payload) {
state.counter += payload
}
}
payload为对象类型
addNumber(state, payload) {
state.counter += payload.count
}
对象风格的提交方式
$store.commit({
type: 'addNumber',
count: 100
})
mutation常量类型
定义常量 mutation-type.js
export const ADD_NUMBER = 'ADD_NUMBER'
定义mutation
[ADD_NUMBER](state, payload) {
state.counter += payload.count
}
提交mutation
$store.commit({
type: ADD_NUMBER,
count: 100
})
mapMutations辅助函数
我们也可以借助于辅助函数 帮助我们快速映射到对应的方法中
methods: {
...mapMutations({
addNumber: ADD_NUMBER
}),
...mapMutations(['increment', 'decrement'])
}
在setup中
const mutations = mapMutations(['increment', 'decrement'])
const mutations2 = mapMutations({
addNumber: ADD_NUMBER
})
mutation重要原则
一条重要原则就是要记住mutation必须是同步函数
- 这是因为devtool工具会记录mutation的日记
- 每一条mutation被记录 devtool都需要捕捉到前一状态与后一状态的快照
- 但是在mutation中执行异步操作 就无法追踪到数据的变化
所以Vuex的重要原则中 mutation必须是同步函数
actions的基本使用
Action类似于mutation 不同在于
- Action提交的是muttion 而不是直接变更状态
- Action可以包含任意异步操作
这里有一个非常重要的参数context
- context是一个和store实例均有相同方法和属性的context对象
- 所以我们可以从中获取到commit方法来提交一个mutation 或者通过context.state 和 context.getters来获取state和getters
actions的分发操作
如何使用action呢 进行action的分发
- 分发使用的是store上的dispatch函数
add() {
this.$store.dispatch('increment')
}
同样的,它也可以携带我们的参数
add() {
this.$store.dispatch('increment', {count: 100})
}
也可以以对象的形式进行分发
add() {
this.$store.dispatch({
type: 'increment',
count: 100
})
}
actions的辅助函数
action也有对应的辅助函数
- 对象类型的写法
- 数组类型的写法
methods: {
...mapActions(['increment', 'decrement'])
...mapActions({
add: 'increment',
sub: 'decrement'
})
}
const actions1 = mapActions(['decrement'])
const actions2 = mapActions({
add: 'increment',
sub: 'decrement'
})
actions的异步操作
action通常是异步的 那么如何知道action什么时候结束
- 我们可以通过action返回Promise 在Promise的then中来处理完成后的操作
actions: {
increment(context) {
return new Promise((resolve) => {
setTimeout(() => {
context.commit('increment')
resolve('异步完成')
}, 1000)
})
}
}
const store = useStore()
const increment = () => {
store.dispatch('increment').then(res => {
console.log(res, '异步完成')
})
}
module的基本使用
什么是Module?
- 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象,当应用变得非常复杂时,store 对象就有可能变得相当臃
肿; - 为了解决以上问题,Vuex 允许我们将 store 分割成模块(module);
- 每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块;
const moduleA = {
state: () => ({}),
mutations: {},
actions: {},
getters: {}
}
const moduleB = {
state: () => ({}),
mutations: {},
actions: {}
}
const store = createStore({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a //-> moduleA 的状态
store.state.b //-> moduleB 的状态
module的局部状态
对于模块内部的mutation和getter 接收的第一个参数是模块的局部状态对象
mutations: {
changeName(state) {
state.name = 'kobe'
}
},
getters: {
info(state, getters, rootState) {
return `name: ${state.name} age: ${state.age} height: ${state.height}`
}
}
actions: {
changeNameAction({state, commit, rootState}) {
commit('changeName', 'kobe')
}
}
module的命名空间
默认情况下,模块内部的action和mutation仍然是注册在全局的命名空间中的:
- 这样使得多个模块能够对同一个 action 或 mutation 作出响应;
- Getter 同样也默认注册在全局命名空间;
如果我们希望模块具有更高的封装度和复用性,可以添加 namespaced: true 的方式使其成为带命名空间的模块: - 当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名;
如果我们希望在action中修改root中的state,那么有如下的方式:
changeNameAction({commit, dispatch, state, rootState, getters, rootGetters}) {
commit('changeName', 'kobe')
commit('changeRootName', null, {root: true})
dispatch('changeRootNameAction', null, {root: true})
}