Vuex 中localStorage的使用

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

1、首先新建一个js文件,如:localstorage.js   通过setItem 和getItem设置和获取数据

const key = "addkey"
var storageObjece = {
  set: function(items) {
    localStorage.setItem(key, JSON.stringify(items))
  },
  get: function() {
    var val = localStorage.getItem(key) || '[]';
      val = JSON.parse(val);
      return val
  }

}

export default storageObjece

setItem设置键值只能是字符串形式,JSON.stringify(items)

getItem获取时再通过JSON.parse()转换成对象

 

2、设置存储数据

在页面中引用localstorage.js

import storage from "../assets/js/localstorage.js"

同时通过watch监听数据的变化,并在handler方法中存储items  storage.set(items)

3、获取存储数据

采用Vuex开发模式,获取localStorage数据,同样需要引入localstorage.js,并在store的state中设置

items:storage.get()

import Vue from 'vue'
import Vuex from "vuex"
import storage from "../assets/js/localstorage.js"
Vue.use(Vuex)

//import Index from '@/views/index/index'
//import Manage from '@/views/manage/index'

//import OtherRouter from '../views/index/otherrouter'

const store = new Vuex.Store({
  state: {
    items: storage.get()
    // [
    //   // { value: "default", id: 0 }
    // ],
    
  },

  mutations: {
    addItems(state, item) {
      state.items.push(item)
    },
    delItem(state,index){
      state.items.splice(index,1)
    },
    saveItem(state,payload){
      //alert("hi")
      state.items[payload.editId].value=payload.textvalue
     
    }
  },
  actions: {
    addItems(context, item) {
      context.commit("addItems", item)
    },
    delItem(context,index){
      context.commit("delItem", index)
    },
     saveItem(context,payload){
      context.commit("saveItem", payload)
    },
  }
});

export default store

 

转载于:https://my.oschina.net/u/2612473/blog/1590179

你可能感兴趣的:(Vuex 中localStorage的使用)