SoFunction
Updated on 2025-04-07

In vue, how to read and write data in local cache

1. Install the good-storage plugin

cnpm i good-storage --save

2. Reading/writing method

common/js/:

import storage from 'good-storage'

const SEARCH_KEY = '__search__'
const SEARCH_MAX_LENGTH = 15

// compare: Findindex passes in function, so you cannot pass val directlyfunction insertArray(arr, val, compare, maxLen) {
 const index = (compare)
 if (index === 0) {
 return
 }
 if (index > 0) {
 (index, 1)
 }
 (val) // Insert to the front of the array if (maxLen &&  > maxLen) {
 () // Delete the last element }
}

//Storing search historyexport function saveSearch(query) {
 let searches = (SEARCH_KEY, [])
 insertArray(searches, query, (item) => {
 return item === query
 }, SEARCH_MAX_LENGTH)
 (SEARCH_KEY, searches)
 return searches
}
// Load local cache search historyexport function loadSearch() {
 return (SEARCH_KEY, [])
}

3. Data is passed in vuex

Write data in store/:

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. Call vuex in the component

import {mapActions} from 'vuex'

// In methods: saveSearch() {
  ()
 },
 ...mapActions([
  'saveSearchHistory'
 ])

In the above vue article, the method of reading and writing data in local cache is all the content I share with you. I hope you can give you a reference and I hope you can support me more.