vue中,在本地緩存中讀寫數(shù)據(jù)的方法
1.安裝good-storage插件
cnpm i good-storage --save
2.讀/寫的方法
common/js/cache.js:
import storage from 'good-storage' const SEARCH_KEY = '__search__' const SEARCH_MAX_LENGTH = 15 // compare:findindex傳入的是function,所以不能直接傳val function insertArray(arr, val, compare, maxLen) { const index = arr.findIndex(compare) if (index === 0) { return } if (index > 0) { arr.splice(index, 1) } arr.unshift(val) // 插入到數(shù)組最前 if (maxLen && arr.length > maxLen) { arr.pop() // 刪除末位元素 } } // 存儲(chǔ)搜索歷史 export function saveSearch(query) { let searches = storage.get(SEARCH_KEY, []) insertArray(searches, query, (item) => { return item === query }, SEARCH_MAX_LENGTH) storage.set(SEARCH_KEY, searches) return searches } // 加載本地緩存的搜索歷史 export function loadSearch() { return storage.get(SEARCH_KEY, []) }
3.數(shù)據(jù)用vuex傳遞
在store/actions.js中寫入數(shù)據(jù):
import * as types from './mutation-types' import {saveSearch} from 'common/js/cache' export const saveSearchHistory = function({commit, state}, query) { commit(types.SET_SEARCH_HISTORY, saveSearch(query)) }
4.組件中調(diào)用vuex
import {mapActions} from 'vuex' // methods內(nèi): saveSearch() { this.saveSearchHistory(this.query) }, ...mapActions([ 'saveSearchHistory' ])
以上這篇vue中,在本地緩存中讀寫數(shù)據(jù)的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決vue A對(duì)象賦值給B對(duì)象,修改B屬性會(huì)影響到A的問(wèn)題
今天小編就為大家分享一篇解決vue A對(duì)象賦值給B對(duì)象,修改B屬性會(huì)影響到A的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-09-09解決vue3中使用echart報(bào)錯(cuò):Cannot read properties of&n
在Vue項(xiàng)目中使用Echarts進(jìn)行數(shù)據(jù)可視化是非常常見的需求,然而有時(shí)候在引入Echarts的過(guò)程中可能會(huì)遇到報(bào)錯(cuò),本文主要介紹了解決vue3中使用echart報(bào)錯(cuò):Cannot read properties of undefined (reading ‘type‘),感興趣的可以了解一下2024-01-01vue+element?tree懶加載更新數(shù)據(jù)的示例代碼
這篇文章主要介紹了vue+element?tree懶加載更新數(shù)據(jù),文中給大家補(bǔ)充介紹了Vue Element Ui 樹形表懶加載新增、修改、刪除等操作后局部數(shù)據(jù)更新的詳細(xì)代碼,感興趣的朋友跟隨小編一起看看吧2022-09-09Vue SPA 初次進(jìn)入加載動(dòng)畫實(shí)現(xiàn)代碼
今天小編就為大家分享一篇Vue SPA 初次進(jìn)入加載動(dòng)畫實(shí)現(xiàn)代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11vue中渲染對(duì)象中屬性時(shí)顯示未定義的解決
這篇文章主要介紹了vue中渲染對(duì)象中屬性時(shí)顯示未定義的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07