什么是vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 通过vuex我们可以解决组件之间数据共享的问题,后期也方便我们管理以及维护 分别是:state,actions,mutations,getters,modules
vuex是由五部分组成
state: 用于存储公共的数据
mutations: 唯一可以改变state的地方
getters: 相当于vuex的计算属性
actions: 异步操作,在页面中调用是$store.dispath('')
modules: store的子模块,用于开发大型项目管理而使用的
如何使用
// 在页面中获取vuex中的数据,有三种方式,分别是
// 建议使用第三种
<template>
<div>
// 第一种:直接在标签使用
<p>{{$store.state.data}}</p>
// 第二种
<p>{{data}}</p>
// 第三种
<p>{{data}}</p>
</div>
</template>
data(){
return {
// 第二种
data:this.$store.state.data
}
}
// 第三种
computed: {
data(){
return this.$store.state.data
}
}
// store/index.js
export default new Vuex.Store({
state: {
data:'hello world'
},
})
把参数传给vuex,在vuex中的mutations进行操作
this.$store.commit('change',this.text)
如果我们在actions中请求数据的话,在页面中就可以通过dispatch调用actions中的方法
this.$store.dispatch('change');
高级用法
数据持久化
安装依赖
1.cnpm i vuex-persistedstate --save
备注:
-S 是 --save的简写,把插件安装到生产环境中
-D 是 --save-dev的简写,把插件安装到开发环境中
使用:
在store/index.js中
// 首先引入
import persist from 'vuex-persistedstate'
// 使用 跟state,mutations同级
plugins: [persist()]
模块化管理数据(modules)
使用:
我们在store里面新建一个text.js文件
在index.js中引入,modules:{text}
// 在text.js中
export default new Vuex.Store({
state: {
data:'hello world'
},
mutations: {
getID(state,val){
this.data = val
}
}
})
在页面中使用:
// 获取modules模块中state的数据
<p>{{data}}</p>
computed:{
data(){
return this.$store.state.text.data
}
}
// 获取modules模块中mutations中的事件
// 使用的话需要在前面加上引入的modules名称
this.$store.commit("text/getID",12345)
辅助函数(语法糖)
有四个辅助函数,分别是:
mapActions, mapGetters, mapMutations, mapState
作用:
辅助函数可以把vuex中的数据和方法映射到vue组件中,达到简化目的的操作
使用
// 这种只可以解析index.js里面,模块里面的数据和方法不能映射到
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'
computed: {
// 有两种方式,一种是对象形式,一种是数组形式
...mapState({
// 在页面中使用的的参数 : 'vuex中的数据(必须要加引号)'
token: 'token'
}),
// 要想映射多个,在后面加上逗号继续写即可
...mapGetters(['token-x']),
},
methods:{
...mapActions({
setToken: 'setToken'
}),
// 把vuex中的方法映射过来 还叫change
...mapMutations(['change']),
}
import {createNamespacedHelpers} from 'vuex'
const {mapState:mapStateUser,mapActions:mapActionUser,mapMutations:mapMutaionuser} = createNamespacedHelpers('test')
// 可以映射模块中的数据
...mapStateCart({cartid:'data'})