Vuex基础
是实现组件全局状态管理的一种机制
如果两个不相干的组件之间想要互相传递数据,传统方法需要传入父组件在通过父组件等组件作为媒介传入其子组件,Vuex就避免了这种复杂的传递方式
存储在Vuex中的数据都是响应式的,能够保持数据页面同步
Vuex的主要核心:
- State :【存放数据】提供唯一数据源,所有共享数据都统一放在Store的State中
- Mutation:【修改数据】用于修改store中的数据。因为store的值可以在任何组件中使用,如果直接用state修改值,开发后期不容易找到是谁修改了这个值,需要一个页一个页找。不能执行异步操作
- Action:【异步操作】专门执行异步操作,但不能修改数据,因此要修改数据需要异步调用Mutation中的方法
- Getter:【包装数据】加工Store中的数据后返回新数据,不会修改原数据,类似计算属性,原数据修改,Getter数据也跟着变化
安装
安装vuex依赖包
npm install vuex --save
创建一个store.js或者创建store文件夹下创建index.js
import {createStore} from 'vuex'
// 向外暴露store实例
export default createStore({
state:{
// 存放一个数据count
count:0
},
})
引入vuex,挂载store
import Vuex from 'vuex'
import store from '/src/store'
app.use(Vuex)
app.use(store)
State
是四个核心中的基础,用来声明存放在store中的数据的,并且使外部组件可以访问到这个数据
组件中访问数据的第一种方式:
this.$store.state.count
第二种方式:
- 引入mapState
- 将count映射为计算属性
- 直接使用count
<template>
<!-- 3 使用count -->
<h1>{{ count }}</h1>
</template>
<script>
import { computed } from 'vue';
// 1 引入mapState
import { mapState } from 'vuex';
export default {
// 2 将count映射为计算属性
computed: {
...mapState(['count'])
}
}
</script>
Mutation
专门用来修改state中的数据的,里面都是修改数据的方法,外部直接调用这里的方法
直接使用
this.$store.state.count +1
也可以让这个值修改,但后期项目越来越大,每个组件都可以使用state中的值,当值发生问题变化的时候,用这种方式修改值就很难找到是谁修改了这个值,因此提供了Mutation,专门用来修改State中的数据
在store.js文件中创建mutations对象
import {createStore} from 'vuex'
// 向外暴露store实例
export default createStore({
state:{
count:1
},
// state的同级下创建mutations
mutations:{
// state为固定传入
// step为传入参数,可以不写
add(state,step){
state.count++
}
}
})
第一种方式:
methods:{
add(){
this.$store.commit('add',3)
}
}
第二种方式:
import { mapMutations } from 'vuex';
export default {
methods:{
// 映射add方法到method,数组中可以引入多个方法
...mapMutations(['add']),
// 可以直接使用,不套新的方法
handleAdd(){
// 调用add方法,如果没有参数就不传入参数
this.add(3)
}
}
}
Action
用来执行异步操作的,因为Mutation不能执行一步操作,所以进行延迟、访问接口等操作的时候都要用这个,Action本身是不能修改数据的,因此Action中是调用mutations中的方法执行异步操作的
import {createStore} from 'vuex'
// 向外暴露store实例
export default createStore({
state:{
count:1
},
mutations:{
add(state,step){
state.count+= step
}
},
// 创建actions对象
actions:{
// context固定,step为参数
addAsync(context,step){
setTimeout(()=>{
// 调用mutations中的方法
context.commit('add',step)
},1000)
}
}
})
第一种方式
methods:{
// 使用dispatch方法调用actions中的异步方法
addsync(){
this.$store.dispatch('addAsync',3)
}
}
第二种方式
import { mapActions } from 'vuex';
export default {
methods:{
// 引入actions中的方法
...mapActions(['addAsync']),
// 可以直接使用,不套新的方法
addsync(){
// 直接使用
this.addAsync(3)
},
}
}
Getter
getter可以看做是装饰器,和java的getter差不多,相当于Vue的计算属性,state中的值变了getter中的数据也会一起改变
import {createStore} from 'vuex'
// 向外暴露store实例
export default createStore({
state:{
count:1
},
mutations:{
add(state,step){
state.count+= step
}
},
actions:{
addAsync(context,step){
setTimeout(()=>{
context.commit('add',step)
},1000)
}
},
// 创建一个getters
getters:{
showNum:state=>{
return '当前值为'+state.count
}
}
})
第一种方式
this.$store.getters.showNum
第二种方式
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters(['showNum'])
}
}
}