什么是vuex
在大项目中使用vuex,解决了组件之间统一状态的共享问题,实现组件之间的数据持久化。在项目中可以用vuex存放数据,不用每次都要请求后端服务器,这就在保证了数据新鲜度的同时提高了使用性能。
vuex,你也可以理解为一个存放全局变量的仓库。在这里可以存放一些各个模块中通用的变量和属性。
vuex持久化作用
当我们在缓存里存储了一些东西时候,一刷新页面找不到了,例如登录的时候,我们需要存登录的状态,又或者是要存储一些重要的文件的时候,持久化就体现出了它的作用。
vuex持久化的配置
1.手动利用HTML5的本地存储
方法
- vuex的state在localStorage或sessionStorage或其它存储方式中取值
- 在mutations,定义的方法里对vuex的状态操作的同时对存储也做对应的操作。
问题
- 最直观的就是,手动写比较麻烦。
2.利用vuex-persistedstate插件
- 安装
npm install vuex-persistedstate --save
- 引入及配置
import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
// ...
plugins: [createPersistedState()]
})
这里默认是存储到localStorage
想要存储到sessionStorage,配置如下
import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
// ...
plugins: [createPersistedState({
storage: window.sessionStorage
})]
})
拆分模块
export default ({
// 自定义一个要获取的数值/数据
state: {
user: ""
},
// 自定义一个获取数值的方法
mutations: {
getuser(state, val) {
state.user = val
}
},
// 这里是一个异步操作
actions: {
getuserAsync({ commit }, val) {
commit('getuser', val)
}
},
// 命名空间
namespaced: true,
})
store文件中引入拆分的模块
import Vue from 'vue'
import Vuex from 'vuex'
// 引入持久化
import createPersistedState from "vuex-persistedstate"
// 引入拆分的模块
import vux from "./module/index.js"
Vue.use(Vuex)
export default new Vuex.Store({
// 引入
modules: {
vux
},
// 持久化操作
plugins: [createPersistedState({
storage: window.sessionStorage
})]
})
引入vuex中存入的值
<template>
<div id="app">
<input type="text" v-model="username">
<input type="text" v-model="pwd">
<button @click="loginfn">登录</button>
<router-view/>
</div>
</template>
<script>
//引入vuex
import {mapState,mapActions} from "vuex"
export default {
data() {
return {
username:"",
pwd:""
}
},
methods: {
//getuserAsync 我们定义的异步操作方法
...mapActions("vux",["getuserAsync"]),
loginfn(){
this.$store.commit("vux/getuser",this.username) //直接使用mutations
this.getuserAsync(this.username) //使用action
this.$router.push("/")
}
},
}
</script>