目录
Vue全局共享数据之globalData,vuex,本地存储使用方法
一、globalData
在js中操作globalData的方式如下:
//store下的index.js存储vuex数据
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const vuexLocal = new VuexPersistence({
storage: window.localStorage,
});
export default new Vuex.Store({
state: {
count:20
},
plugins: [vuexLocal.plugin],
});
//vue3
state: {
passwordState:false,//登录状态
},
mutations:{
// 设置修改登录状态的方法
setPasswordState(state,value){
state.passwordState = value;
},
}
//VUE2中VueX用法
import {mapState } from "vuex";
export default {
computed: {
...mapState({count:'count'}),//方法2
},
computed: mapState({
count: 'count', //方法3
count: (Store) => Store.count, // 方法4
count: function (Store) { // 方法5
return '123:' + Store.count
},
}),
methods:{
submit2(){
console.log(this.$store.state.count,"===");//方法1
console.log(this.count,"count")
}
},
}
//vue3中VueX用法
const storeState=mapState(['count','name'])
const state={}
Object.keys(storeState).forEach(Key=>{
const fn=storeState[Key].bind({$store:store})
state[Key]=computed(fn)
})
//返回...state就行了
//(2)使用computed一个一个解析
import {useStore} from 'vuex'
import {computed} from 'vue'
const store=useStore()
const state=computed(()=>store.state.name)
======================================================
import { onMounted } from 'vue'
import { useStore } from 'vuex'
export default {
setup(){
//把useStore赋值
const $store = useStore();
onMounted(()=>{
//拿到vuex的值
console.log($store.state.passwordState) // false
//改变vuex的值
$store.commit('setPasswordState',true) //调用vuex的方法
//再次打印
console.log($store.state.passwordState) // true
})
return{
}
}
}
localStorage:可长期存储数据,除非用户清楚localStorage信息,否则数据会一直存在。同一中浏览器之间,不同页面,数据可以共享。
sessionStorage:短期存储数据,用户关闭标签页后或直接关闭浏览器后数据会清空。同一浏览器不同页面之间,数据不可共享
存储用法:
// 将this.pickerItem的数据存储入insuranceCode,需提前转化成string类型
pickerItem:{
id: that.item.id,
limit: 100,
page: 1,
}
//长期存储
localStorage.setItem("insuranceCode", JSON.stringify(this.pickerItem));
//短期存储
sessionStorage.setItem("insuranceCode", JSON.stringify(this.pickerItem));
读取用法,如何获取到:
//长期存储
localStorage.getItem("insuranceCode")
//短期存储
sessionStorage.getItem("insuranceCode")
清除用法:
// 清除insuranceCode
localStorage.removeItem("insuranceCode");
sessionStorage.removeItem("insuranceCode");
// 清除所有
localStorage.clear();
sessionStorage.clear();
最后补充个uniapp的数据缓存。🍉🍉🍉
这里就整个经常用的,其他的可以看下面的图片。 懒....
//uni.setStorageSync(KEY,DATA) 存储
try {
uni.setStorageSync('storage_key', 'hello');
} catch (e) {
// error
}
//uni.getStorageSync(KEY)
//从本地缓存中同步获取指定 key 对应的内容。
try {
const value = uni.getStorageSync('storage_key');
if (value) {
console.log(value);
}
} catch (e) {
// error
}