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

编程学习 2021-07-04 16:46www.dzhlxh.cn编程入门
今天长沙网络推广就为大家分享一篇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'
 ])

以上这篇vue中,在本地缓存中读写数据的方法就是长沙网络推广分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持狼蚁SEO。

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板