1.安装good-storage插件
cnpm i good-storage --save2.读/写的方法
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) // 插入到数组最前
 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.数据用vuex传递
在store/actions.js中写入数据:
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内:
 saveSearch() {
 this.saveSearchHistory(this.query)
 },
 ...mapActions([
 'saveSearchHistory'
 ])
以上这篇vue中,在本地缓存中读写数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。