本篇文章给大家分享的是有关使用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 insertArrayarr, val, compare, maxLen) {
const index = arr.findIndexcompare)
if index === 0) {
return
}
if index > 0) {
arr.spliceindex, 1)
}
arr.unshiftval) // 插入到数组最前
if maxLen && arr.length > maxLen) {
arr.pop) // 删除末位元素
}
}
// 存储搜索历史
export function saveSearchquery) {
let searches = storage.getSEARCH_KEY, [])
insertArraysearches, query, item) => {
return item === query
}, SEARCH_MAX_LENGTH)
storage.setSEARCH_KEY, searches)
return searches
}
// 加载本地缓存的搜索历史
export function loadSearch) {
return storage.getSEARCH_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) {
committypes.SET_SEARCH_HISTORY, saveSearchquery))
}
4.组件中调用vuex
import {mapActions} from 'vuex'
// methods内:
saveSearch) {
this.saveSearchHistorythis.query)
},
...mapActions[
'saveSearchHistory'
])
Vue的优点
Vue具体轻量级框架、简单易学、双向数据绑定、组件化、数据和结构的分离、虚拟DOM、运行速度快等优势,Vue中页面使用的是局部刷新,不用每次跳转页面都要请求所有数据和dom,可以大大提升访问速度和用户体验。
