简体   繁体   English

在 vuejs 中使用 vuex-persistedstate 创建多个唯一状态

[英]Create multiple unique states using vuex-persistedstate in vuejs

I am learning vue.js and trying to use vuex-persistedstate to save some states.我正在学习 vue.js 并尝试使用vuex-persistedstate来保存一些状态。 I created a simple todo app and each one has a unique id.我创建了一个简单的待办事项应用程序,每个应用程序都有一个唯一的 ID。

I am iterating through all of them and create a vue instance like this:我正在遍历所有这些并创建一个这样的 vue 实例:

<div id="todo-list-1" class="todo-list">...</div>
<div id="todo-list-2" class="todo-list">...</div>
<div id="todo-list-3" class="todo-list">...</div>

document.querySelectorAll('.todo-list').forEach(list => {
   new Vue({
     el: `#${list.id}`,
     render: h => h(App)
   })
})

I want to create a state when all todo items in each todo list are completed, for example one for todo-list-1 and one for todo-list-2 and so on.我想在每个待办事项列表中的所有待办事项都完成时创建一个状态,例如一个用于todo-list-1 ,一个用于todo-list-2等等。

const store = new Vuex.Store({
  state: {
    completed: false
  },
  plugins: [createPersistedState()],
  mutations: {
    completed: state => state.completed = true,

  }
});

How can I create local storage states based on id for each todo list?如何根据每个待办事项列表的 id 创建本地存储状态?

One option that you have is to create multiple instances of your Vuex store.您拥有的一种选择是创建 Vuex 商店的多个实例。

Something like就像是

document.querySelectorAll('.todo-list').forEach(list => {
   new Vue({
     el: `#${list.id}`,
     store,
     render: h => h(App)
   })
})

You might run into problems trying to manage multiple Vuex stores.尝试管理多个 Vuex 商店时可能会遇到问题。 See here for reference.请参阅此处以供参考。

You might be better served taking a step back and thinking about the structure of your data.您最好退后一步思考数据的结构。 You can set up a single Vue instance, and add a boolean to your to-do list item data object.您可以设置单个 Vue 实例,并向您的待办事项列表项数据对象添加一个布尔值。

You could also consider making localStorage reactive if it would help with your implementation.如果它有助于您的实现,您也可以考虑使 localStorage 具有反应性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM