1.安裝good-storage插件
cnpm i good-storage --save
2.讀/寫(xiě)的方法
common/js/cache.js:
import storage from 'good-storage'const SEARCH_KEY = '__search__'const SEARCH_MAX_LENGTH = 15// compare:findindex傳入的是function,所以不能直接傳valfunction 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中寫(xiě)入數(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中,在本地緩存中讀寫(xiě)數(shù)據(jù)的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持錯(cuò)新站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選