vue中,在本地緩存中讀寫數(shù)據(jù)的方法
更新時間:2018年09月21日 16:02:18 作者:衛(wèi)夫子
今天小編就為大家分享一篇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() // 刪除末位元素 } } // 存儲搜索歷史 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.組件中調用vuex
import {mapActions} from 'vuex' // methods內(nèi): saveSearch() { this.saveSearchHistory(this.query) }, ...mapActions([ 'saveSearchHistory' ])
以上這篇vue中,在本地緩存中讀寫數(shù)據(jù)的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
解決vue3中使用echart報錯:Cannot read properties of&n
在Vue項目中使用Echarts進行數(shù)據(jù)可視化是非常常見的需求,然而有時候在引入Echarts的過程中可能會遇到報錯,本文主要介紹了解決vue3中使用echart報錯:Cannot read properties of undefined (reading ‘type‘),感興趣的可以了解一下2024-01-01vue+element?tree懶加載更新數(shù)據(jù)的示例代碼
這篇文章主要介紹了vue+element?tree懶加載更新數(shù)據(jù),文中給大家補充介紹了Vue Element Ui 樹形表懶加載新增、修改、刪除等操作后局部數(shù)據(jù)更新的詳細代碼,感興趣的朋友跟隨小編一起看看吧2022-09-09