当前位置:主页 > 网页前端 > vue >

vue中,在本地缓存中读写数据的方法

时间:2020-10-08 13:29:13 | 栏目:vue | 点击:

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) // 插入到数组最前
 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'
 ])

您可能感兴趣的文章:

相关文章