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.組件中調(diào)用vuex
import {mapActions} from 'vuex'
// methods內(nèi):
saveSearch() {
this.saveSearchHistory(this.query)
},
...mapActions([
'saveSearchHistory'
])
以上這篇vue中,在本地緩存中讀寫數(shù)據(jù)的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue?require.context()的用法實(shí)例詳解
require.context是webpack提供的一個(gè)api,通常用于批量注冊組件,下面這篇文章主要給大家介紹了關(guān)于vue?require.context()用法的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04
vue 2 實(shí)現(xiàn)自定義組件一到多個(gè)v-model雙向數(shù)據(jù)綁定的方法(最新推薦)
有時(shí)候我們需要對一個(gè)組件綁定自定義 v-model,以更方便地實(shí)現(xiàn)雙向數(shù)據(jù),例如自定義表單輸入控件,這篇文章主要介紹了vue 2 實(shí)現(xiàn)自定義組件一到多個(gè)v-model雙向數(shù)據(jù)綁定的方法,需要的朋友可以參考下2024-07-07
vue2 使用@vue/composition-api依賴包 編譯、打包各種報(bào)錯(cuò)問題分析
由于package.json 文件中 vue、vue-template-compiler 版本號前面 多了個(gè) ^ 導(dǎo)致實(shí)際導(dǎo)入時(shí),node_module中的 vue 版本可能被升級為 2.7.x,這篇文章主要介紹了vue2 使用@vue/composition-api依賴包 編譯、打包各種報(bào)錯(cuò)問題分析,需要的朋友可以參考下2023-01-01
vue Element UI 解決表格數(shù)據(jù)不更新問題及解決方案
在使用Vue和ElementUI開發(fā)后臺管理系統(tǒng)時(shí),可能會遇到表格數(shù)據(jù)不更新的問題,這通常是因?yàn)閂ue的響應(yīng)式系統(tǒng)未檢測到數(shù)據(jù)變化或數(shù)據(jù)更新后未正確觸發(fā)視圖的重新渲染,本文給大家介紹vue Element UI 解決表格數(shù)據(jù)不更新問題,感興趣的朋友一起看看吧2024-10-10
Vue.extend 編程式插入組件的實(shí)現(xiàn)
這篇文章主要介紹了Vue.extend 編程式插入組件的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11

