vue中,在本地缓存中读写数据的方法
1.安装good-storage插件
cnpmigood-storage--save
2.读/写的方法
common/js/cache.js:
importstoragefrom'good-storage' constSEARCH_KEY='__search__' constSEARCH_MAX_LENGTH=15 //compare:findindex传入的是function,所以不能直接传val functioninsertArray(arr,val,compare,maxLen){ constindex=arr.findIndex(compare) if(index===0){ return } if(index>0){ arr.splice(index,1) } arr.unshift(val)//插入到数组最前 if(maxLen&&arr.length>maxLen){ arr.pop()//删除末位元素 } } //存储搜索历史 exportfunctionsaveSearch(query){ letsearches=storage.get(SEARCH_KEY,[]) insertArray(searches,query,(item)=>{ returnitem===query },SEARCH_MAX_LENGTH) storage.set(SEARCH_KEY,searches) returnsearches } //加载本地缓存的搜索历史 exportfunctionloadSearch(){ returnstorage.get(SEARCH_KEY,[]) }
3.数据用vuex传递
在store/actions.js中写入数据:
import*astypesfrom'./mutation-types' import{saveSearch}from'common/js/cache' exportconstsaveSearchHistory=function({commit,state},query){ commit(types.SET_SEARCH_HISTORY,saveSearch(query)) }
4.组件中调用vuex
import{mapActions}from'vuex' //methods内: saveSearch(){ this.saveSearchHistory(this.query) }, ...mapActions([ 'saveSearchHistory' ])
以上这篇vue中,在本地缓存中读写数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。