缘由
如果在一个项目开发中频繁的使用组件传参的方式来同步data中的值,一旦项目很庞大,管理和维护这些值将是相当棘手的工作。为此,Vue为这些被多个组件频繁使用的值
提供了一个统一管理的工具——VueX。在具有VueX的Vue项目中,我们只需要把这些值定义在VueX中,即可在整个Vue项目的组件中使用。
vuex基础
import Vue from "vue";
import Vuex from "vuex"
Vue.use(Vuex)
//公共的数据仓库
const store = new Vuex.Store({
// 定义公共的数据
state:{
username:""
},
// 同步修改state中的数据
mutations:{
},
// 异步修改state中的数据,发送异步请求
actions:{
},
// 获取数据,类似于computed(计算属性,基于state中的数据进行计算得到新的数据)
getters:{
},
// vuex的模块化拆分
modules:{
},
// vuex的插件扩展
plugins:{}
})
因为Vuex是基于内存,存在内存里面的,刷新页面之后数据重置,不会持久化储存我们使用插件vuex-persistedstate 解决这个问题
1.1 下载插件
npm install --save vuex-persistedstate
1.2 创建模块
//store文件夹下面创建mokuai1.js文件
export default {
state:{
shuju1:1,
zobj:[1,2,3]
}
}
1.3插件详细配置和使用 vuex数据状态持久化
import Vue from "vue";
import Vuex from "vuex";
// 外部引入的模块
import mokuai1 from "./mokuai1";
// 引入持久化插件
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex)
//公共的数据仓库
const store = new Vuex.Store({
// 定义公共的数据
state:{
username:""
},
// 同步修改state中的数据
mutations:{
},
// 异步修改state中的数据,发送异步请求
actions:{
},
// 获取数据,类似于computed(计算属性,基于state中的数据进行计算得到新的数据)
getters:{
},
// vuex的模块化拆分
modules:{
mokuai1
},
// vuex的插件扩展
plugins: [createPersistedState({
// 存储数据的键名,比如通过localStorage.getItem("key名")获取
key:"longStore",
// 存储方式 localStorage(默认),sessionStorage,cookies
storage:window.localStorage,
// 要存储的数据
reducer(val){
//设置需要缓存的数据
// return val //全部缓存 val表示整个vuex数据外层
// return val.username //缓存state中的username
// return val.modules的模块名 // 缓存modules的mokuai1模块中state全部字段
// 缓存modules的mokuai1模块中部分字段
// return{
// modules的模块名:{
// 字段名:val.模块名.字段名
// }
// }
}
})],
})
1.4 全缓存简写(此处缓存的是state里面的数据加上模块里面的数据)
// vuex文件中
// 引入持久化插件
import createPersistedState from "vuex-persistedstate";
plugins: [createPersistedState()]
1.5 点击首页,测试数据变成新数据,刷新页面后还是新数据
// home.vue中
<h3 @click="fun">首页</h3>
<h3>{{ this.$store.state.CS1 }}</h3>
methods: {
fun(){
this.$store.commit('mutCS1','新数据')
}
}
//============================================
// vuex 中
state:{
CS1:"测试数据"
},
mutations:{
mutCS1(state,data){
state.CS1 = data
}
},
2.1数据缓存加密
// 在utils文件夹下创建encryption.js文件
// 引入加密的插件
import SecureLS from 'secure-ls'
export function useStorage(options = {
encodingType: 'base64', //加密类型
isCompression: false, //是否压缩,默认true
encryptionSecret: 's3cr3tPa$$w0rd@123' //HASH加密秘钥,用来防止加密爆破
}) {
const ls = new SecureLS(options)
return {
getItem: (key) => ls.get(key),
setItem: (key, value) => ls.set(key, value),
removeItem: (key) => ls.remove(key),
removeAll: () => ls.removeAll()
}
}
2.2加密后如何使用
// 使用方法
import { useStorage } from '@/utils/encryption.js'
const { setItem, getItem, removeItem,removeAll } = useStorage()
// 设置键值
setItem('data', '123')
// 获取键对应的值
const data = getItem('data')
console.log(data)
// 删除键对应的值
removeItem("data")