目录
1.this.$store.commit('addN', 5)
1.this.$store.dispatch('addAsync')
1.概念和优点
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享
优点:
- 能够在Vuex中集中管理共享的数据,易于开发和后期维护
- 能够高效的实现组件之间的数据共享,提高开发效率
- 存储在Vuex中的数据是响应式的,能够实时保持数据与页面的同步
2.state 数据源
store.js
//创建store数据源,提供唯一公共数据
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
},
actions: {
},
modules: {
}
})
state两种引用方式
1.this.$store.state.count
export default {
data() {
return {}
},
computed: {
count () {
return this.$store.state.count
}
},
}
2.mapState
//1.导入辅助函数 mapState
import { mapState } from 'vuex'
export default {
data() {
return {}
},
computed: {
// mapState 可以接收数组或对象形式的参数 映射为计算属性,下面分别示例
//2.1 传入数组
...mapState(['count']),
//2.2 对象形式 可以自定义名称
...mapState({
xCount:state => state.count
})
},
}
3.mutations变更state中的数据
注意:
- 只有 mutations 里的函数,才有权利修改 state 中的数据
- mutations中不能包含异步操作
store.js
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
add(state){
//变更状态
state.count++
},
addN(state, step){
//变更状态
state.count += step
},
}
})
触发mutations两种方式
1.this.$store.commit('addN', 5)
IncrementN(){
this.$store.commit('addN',5)
}
2.mapMutations
store.js
import { mapMutations } from 'vuex'
methods:{
...mapMutations(['add','addN']),
increment(){
// 调用
this.add()
},
incrementN(){
this.addN(5)
}
}
4.actions 异步操作mutations
注意:
- 异步变更state数据只能通过actions操作
- 在actions中只能通过触发mutations的方式间接变更数据,不能直接修改state数据
store.js
const store = new Vuex.store({
// ...省略其他代码
mutations: {
// 只有 mutations中的函数才有权利修改 state。
// 不能在 mutations里执行异步操作。
add(state) {
state.count++
}
},
actions: {
// 在Actions 中不能直接修改 state中的数据,要通过 mutations修改。
addAsync(context) {
setTimeout(() => {
context.commit('add')
}, 1000);
}
},
})
触发actions的两种方式
1.this.$store.dispatch('addAsync')
// 触发 Action
methods:{
handle(){
// 触发 actions 的第一种方式
this.$store.dispatch('addAsync')
}
}
2.mapActions
import {mapActions} from 'vuex'
methods:{
...mapActions(['subAsync']),
decrementAsync(){
this.subAsync()
}
}
5.getters 包装state数据,不会修改
注意:
- getters对state中的数据加工成新的数据,类似Vue的计算属性
- state中数据发生变化,getters中数据也会跟着变化
//定义 Getter
const store = new Vuex.Store({
state:{
count:0
},
getters: {
showNum(state) {
return '当前最新的数量是【' + state.count + '】'
}
},
})
使用getters的两种方式
1.this.$store.getters.showNum
<template>
<div>
<h1>当前最新的数量是 {{ this.$store.getters.showNum }}</h1>
</div>
</template>
<script>
</script>
2.mapGetters
<template>
<div>
<h1>当前最新的数量是 {{ showNum }}</h1>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
computed:{
...mapGetters(['showNum'])
}
</script>
6. Vue3 使用 Vuex
import { computed } from 'vue'
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
return {
// 在 computed 函数中访问 state
count: computed(() => store.state.count),
// 在 computed 函数中访问 getter
double: computed(() => store.getters.double)
// 使用 mutation
increment: () => store.commit('increment'),
// 使用 action
asyncIncrement: () => store.dispatch('asyncIncrement')
}
}
}