一、 什么是vuex
1、Vuex是一个专为Vue.js 应用程序开发的状态管理模式,它由五部分组成:
分别是:state、actions,mutations,getters,modules
(1)、state:数据
(2)、actions:可以包含异步操作
(3)、mutations:唯一可以修改state数据的场所
(4)、getters:类似于vue组件中的计算属性,对state数据进行计算(会被缓存)
(5)、modules:模块化管理store(仓库),每块模块拥有自己的state、mutation、action、getter
二、如何使用
(1)、store–>index
import vue from 'vue'
import Vuex from 'vuex'
Vue.use(vuex);
const state= ()=>{ token:''}
const actions = {
set_token({commit},val){
commit("to_token",val)
}
}
const mutations = {
to_token(state,val){
state.token=val;
}
}
const getters = {}
let store = new Vuex.store({
state,
actions,
mutations,
getters
})
module.export=store;
(2)、home.vue
<template>
<div>
// 第一种:直接在标签使用
<p>{{$store.state.data}}</p>
// 第二种
<p>{{ data }}</p>
// 第三种
<p>{{ data }}</p>
</div>
</template>
<script>
export default={
name: 'Home',
data() {
return {
// 第二种
data:this.$store.state.data
}
},
// 第三种
computed: {
data() {
return this.$store.state.data
}
}
created(){
//调用actionts中的方法
this.$store.dispatch('set_data',12345);
//调用mutations中的方法
this.$store.commit('to_data',123456)
}
}
// 在页面中调用mutaions中的方法
this.$store.commit('change',this.text)
//在页面中调用actions中的方法
this.$store.dispatch('change',this.text);
<script>
三、高级用法 ----- 数据持久化
问题:存储在vuex中的状态,刷新页面,会丢失
解决方案:数据持久化
最简单的做法就是利用插件 vuex-persistedstate
1、安装:cnpm install vuex-persistedstate -S
注:-S 是 --save的简写,意为:把插件安装到 dependencies (生产环境依赖)中
-D 是 --save-dev的简写,意为:把插件安装到 devDependencies (开发环境依赖)中
2、使用
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
state,
mutations,
actions,
getters,
plugins: [createPersistedState({
storage: sessionStorage,
key: "token"
})]//会自动保存创建的状态。刷新还在
})
参数:
storage:存储方式。(sessionStorage,localStarage)key:定义本地存储中的key
四、模块化管理(modules)
使用:
我们在store里面新建一个text.js文件
在index.js中引入,modules:{ text }
//在text.js中
export default new Vuex.Store({
state: {
data:'hello word'
},
mutaions: {
gitID(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)
五、辅助函数(语法糖)
1、有四个辅助函数,分别是: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'})