vuex
vue 的状态管理工具 管理项目中的公共数据 能够实现页面的数据共享
一共有五大核心
state 存放公共数据的地方 通过 this.$store.state.xxx调用
mutations 修改 state 的地方 只有这里能修改 通过this.$store.commit 调用
getters 相当于是之前的计算属性 通过 this.$store.getters 调用
actions 执行异步操作的地方 通过 this.$store.dispatch 调用
modules 模块化
vuex执行机制
如果我们想要改变state的状态,通过this.$store.dispatch调用actions里面的方法,通过commit触发mutation里面的方法来改变state的状态
vuex缺点
- 适合中大型的项目
- 刷新的适合数据会丢失
我们为了保证刷新数据不丢失,可以使用固化插件实现自动本地存储
如果不让使用固化工具,实现持久化存储:
只需要在调用mutations方法的时候本地存储一下就可以了
vuex的辅助函数 4个
四大金刚辅助函数:mapState,mapActions,mapMutations,mapGetters
四个辅助函数在页面中使用:
mapState,mapGetters映射到computed里面
mapActions,mapMutations映射到methods里面
<p>{{ num }}</p> //直接获取state里面的num
<p>{{ hjw}}</p> //直接获取getters里面的hjw
//1、先引入
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
export default {
//2、使用
computed: {
...mapState(['num']),
// ...mapGetters(['comNum'])
...mapGetters({hjw: 'comNum'})
},
methods: {
...mapMutations(['addNum']),
...mapActions(['reduceNum']),
add(){
// this.$store.commit('addNum',this.a)
this.addNum(this.a)
},
reduce(){
// this.$store.dispatch('reduceNum',this.a)
this.reduceNum(this.a)
},
},
};
</script>
modules模块划分
vuex适合中大型项目 页面逻辑会比较臃肿需要划分模块 所以需要模块划分 这样会使项目逻辑清晰 数据不会混乱 一般情况下 使用的话在新建一个js文件 在里面const一个名字 它是一个对象 每个模块里面都会有vuex的五大核心 最后用export defult 名字
如果使用在主页面引入 import 名字 from xx.js
把名字写在主页面的modules 里面就可以使用了
因为使用了模块划分 getters mutations actions 里面的属性或方法都与vuex五大核心里面的属性方法放在一起 难免会出现命名相同的情况 所以我们要开启命名空间 避免这种情况发生
modules: {
goods: {
namespaced: true, //开启命名空间 与state同级
state: {
goodsNum: 0
},
getters:{
comNum(state){
return '$' + state.goodsNum
}
},
mutations: {
addNum(state,data){
state.goodsNum+=data
},
},
actions: {
reduceNum({commit}){
commit('addNum',-1)
}
},
modules: {
}
}
},
获取划分模块state里面的值
<p>goods--state--数据{{this.$store.state.goods.goodsNum}}</p>
获取 开启命名空间后 划分模块getters里面的值
<p>goods--getters--数据 {{this.$store.getters['goods/comNum']}}</p>
获取 开启命名空间后 划分模块mutations里面的值
<button type="button" @click="addGoods">加</button>
addGoods(){
this.$store.commit('goods/addNum',1)
},
获取 开启命名空间后 划分模块actions里面的值
<button type="button" @click="reduceGoods">减</button>
reduceGoods(){
this.$store.dispatch('goods/reduceNum')
}