vuex中的数据持久化

将vuex中的数据保存到localstorage中
local storage.js代码

export default{
 save:function(obj){
  let str = JSON.stringify(obj)
  localStorage.setItem("todoList",str)
},
get:function(){
  let str = localStorage.getItem("todoList")
  let rs = JSON.parse(str)
  if(rs==null){
    return{
      visibility:"all",
      todos:[],
      isclick:false
    }
  }
  else{
    return rs
  }
}
}

vuex 代码

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
import localstorage from'./localstore'
export default new Vuex.Store({
  state:localstorage.get(),
  // state: {
  //   visibility:"all",
  //   todos:[{thing:'睡觉',done:false},{thing:"吃饭",done:false}],
  //   isclick:false
  // },
  getters:{
  filterTodo:function(state){
    if(state.visibility=="all")
    return state.todos
    else if(state.visibility=="active")
    return state.todos.filter(item=>item.done==false)
    else
    return state.todos.filter(item=>item.done==true)
  },
  num:function(state){
    let n= 0 
    state.todos.forEach(item=>{
     if (item.done)
          n++
    })
    return n
  }
  },
  mutations: {
    addTodo:function(state,txt){
      state.todos.push({thing:txt,done:false})
      localstorage.save(state)
    },
    change:function(state,todo){
    todo.done=!todo.done
    localstorage.save(state)
    },
    changevisibility:function(state,visibility){
     state.visibility=visibility
     localstorage.save(state)
    },
    deletecompleted:function(state){
      let rs = state.todos.filter(item=>item.done==false)
      state.todos=rs
      localstorage.save(state)
    },
    deleteselect:function(state,key){
     state.todos.splice(key,1)
     localstorage.save(state)
    },
    selectall:function(state){
      state.isclick=!state.isclick
      state.todos.forEach(item=>item.done=state.isclick)
      localstorage.save(state)
    }
  },
  actions: {
  },
  modules: {
  }
})

vue中的rem适配:https://www.cnblogs.com/txya/p/12166772.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值