hi,我又来blog啦,ly和大家分享一首歌,我可以自己为自己买花。
存和取,一种是长期存储,短期存储,他们是在本地进行存储的。一种是vueX,状态管理工具。
localStorage:可长期存储数据,除非用户清楚localStorage信息,否则数据会一直存在。同一中浏览器之间,不同页面,数据可以共享。
sessionStorage:短期存储数据,用户关闭标签页后或直接关闭浏览器后数据会清空。同一浏览器不同页面之间,数据不可共享。
vuex和localstorage的区别
1.最重要的区别:vuex存储在内存,localstorage则以文件的方式存储在本地。
2.应用场景:vuex用于组件之间的传值,localstorage则主要用于不同页面之间的传值。
3.永久性:当刷新页面时vuex存储的值会丢失,localstorage不会。
注:很多人觉得用localstorage可以代替vuex, 对于不变的数据确实可以,但是当两个组件共用一个数据源(对象或数组)时,如果其中一个组件改变了该数据源,希望另一个组件响应该变化时,localstorage无法做到,原因就是区别。
存
localStorage.setItem("insuranceCode", JSON.stringify(this.pickerItem));
sessionStorage.setItem("insuranceCode", JSON.stringify(this.pickerItem));
取
JSON.parse(localStorage.getItem("insuranceCode"));
JSON.parse(sessionStorage.getItem("insuranceCode"));
清除
// 清除insuranceCode
localStorage.removeItem("insuranceCode");
sessionStorage.removeItem("insuranceCode");
// 清除所有
localStorage.clear();
sessionStorage.clear();
vuex状态管理工具
1.state是存储的单一状态,是存储的基本数据。
2.getters是store的计算属性,对state的加工,是派生出来的数据。就像computed计算属性一样,getter返回的值会根据它的依赖被缓存起来,且只有当它的依赖值发生改变才会被重新计算。
3.mutations提交更改数据,使用store.commit方法更改state存储的状态。(mutations同步函数)。
4.actions像一个装饰器,提交mutation,而不是直接变更状态。(actions可以包含任何异步操作)。
5.Module是store分割的模块,每个模块拥有自己的state、getters、mutations、actions。
vueX中的核心是store(仓库)
this.$store.commit('模块名/模块中的mutations',值)
this.$store.commit('star_sky/模块中的mutations',[{'ceshikey':'第二种方法'}])
1.state 直接使用
this.$store.state.xxx;
computed: {
...mapState('模块名', ['xxx']),
...mapState('模块名', {'新名字': 'xxx'})
}
2.getters 直接使用
this.$store.getters.模块名,xxx
computed:{
...mapGetters('模块名',['xxx']),
...mapGetters)('模块名',{'新名字':'xxx'})
}
3.Mutation 直接使用
this.$store.commit('mutation名',参数)
methods:{
...mapMutations([''mutation名]),
...mapMutations({'新名字':'mutations名'})
}
4.action 直接使用
this.$store.dispatch('action名',参数)
methods:{
...mapAction('模块名',['xxx']),
...mapAction('模块化',{'新名字':'xxx'})
}
vueX的使用
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const state = {
id:null,
code:null,
}
const mutations = {
//保存数据
CHANGE_ACTIVE_LI(state, { id, code }) {
state.id = id
state.code = code
},
//清除数据
SET_CLEAR_DATA(state,data){
state.id=data
}
}
const actions = {
//保存数据
changeSetting({ commit }, data) {
commit('CHANGE_ACTIVE_LI', { id: data.id, code: data.code })
},
//清除数据
clearVuex({ commit }) {
commit("SET_CLEAR_DATA", null);
},
}
export default {
//解决模块名冲突
namespaced: true,
state,
mutations,
actions
next() {
//这里的product/changeSetting是指定vuex中的方法,我这里指定把 后面的对象加在prouduct中changeSetting方法里面去
this.$store.dispatch("product/changeSetting", {
id: this.id,
code: this.code,
});
},
取出vuex的product.js的id的值
this.id=this.$store.product.id;