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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

卫夫子   2021-03-30 我要评论

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'
 ])

以上这篇vue中,在本地缓存中读写数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们