引言
vuex是vue的状态管理工具,通过vuex我们可以解决组件之间数据共享问题,后期也方便我们管理以及维护。
它包括state,mutations,getters,actions,modules
基本使用
我通过是在根目录下新建一个store文件夹,里面创建一个index.js文件,
最后在main.js中引入,并挂载到实例上,之后那个组件中需要用到vuex就调用就行
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
// 存放数据源 this.$store.state.xxx
state: {},
// 唯一修改state的地方 this.$store.commit('事件名',参数)
mutations: {},
// 执行异步操作 this.$store.dispatch('事件名')
actions: {},
// 模块,每个模块拥有自己的state,mutations,actions,getters
modules: {},
// 计算state
getters:{} this.$store.getters.xxx
})
注意:
我们在使用vuex里面的数据时,可以直接写在模板template
<div>{{$store.state.xxx}}</div>
也可以定义在data里面,但是它监听不到数据的变化
data() {
return {
xxx:this.$store.state.xxx
}
}
vuex中的数据最好不要用data来接受,因为数据是后来者居上,没有实现数据双向绑定,不会触发生命周期中beforeupdate,updated钩子函数。
我们推荐在computed里面接收vuex数据
computed:{
xxx() {
return this.$store.state.xxx
}
}
高级用法
持久化插件
vuex-persistedstate
下载完成后在store/index.js
import persist from 'vuex-persistedstate'
plugins: [persist({
// 定义数据存储的方式 值可以是localStorage 也可以是sessionStorage
storage: localStorage,
// 定义需要指定存储的数据 因为正常工作中vuex不是每一条数据都需要存储 所以我们需要指定需要存储的数据
reducer(state) {
return {
goods: state.goods
}
}
})]
辅助函数
辅助函数可以把vuex中的数据和方法映射到vue组件中。达到简化操作的目的
mapState,mapActions,mapMutations,mapGetters
mapState 辅助函数,可以通过循环vuex中的state中的数据将数据一一取出,方法需要在computed计算属性中使用
import { mapState } from 'vuex'
computed:{
...mapState(对象/数组) // 对象展开运算符
}
如果展开数组,组件中不可以重命名,
如果展开时对象,可以重命名
import { mapGetters } from 'vuex'
computed:{
...mapGetters([])
}
import { mapMutations } from 'vuex'
methods:{
...mapMutations(['mutations方法'])
...mapMutations(['user'])
}
我们可以通过:
this.user(参数) // 进行传递参数
# action函数基本
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters.
actions:{
add(context){
// 每一个action函数都有一个默认参数context,是一个关联vuex上下文的实例
可以通过context.commit.xxx触发mutations来修改state
}
}
# 在组件中分发action
mapActions 辅助函数,通过遍历actions取出action函数到到当前页面中
import { mapActions } from 'vuex'
methods:{
...mapActions(['actions方法'])
}
模块拆分
当我们项目非常庞大,数据信息量特别大的时候,我们可以考虑分模块形式管理数据。
# 命名空间
如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块
表示是独立的作用域
// store/user.js
export default {
namespaced: true,
state: {
name: '张三',
},
getters: {},
mutations: {},
actions: {},
modules: {},
}
// main.js
import user from './user'
export default createStore({
modules:{
user,
}
})
// 访问子模块里面的数据和方法
this.$store.state.user.name
this.$store.commit('user/方法名',值) // 添加作用域user
this.$store.getters['user/name']
// 利用辅助函数访问子模块的数据和方法
方法一:
...mapState('user',{newName:'name'})
...mapMutations('user',['changeName'])
or
...mapMutations({
desA: 'moduleA/des',
desB: 'moduleB/des'
})
方法二:
import {createNamespacedHelpers} from 'vuex'
const {mapState:mapStateUser,mapActions:mapActionUser,mapMutations:mapMutaionuser} = createNamespacedHelpers('user')
就可以直接获取:
...mapStateUser({newName:'name'})
...mapMutaionuser(['changeName'])