【问题标题】:Get an item from localstorage & update/delete从本地存储中获取项目并更新/删除
【发布时间】:2021-04-02 17:56:37
【问题描述】:

我不熟悉在 Javascript 中使用 localStorage。我正在做一个待办事项的 CRUD(我正在使用 jsonplaceholder 来获取待办事项列表)。问题是我必须在单击该元素的按钮(删除/编辑)时获取特定元素。我附上一张图片,看看我是如何渲染我的元素的:

我想要的是,当我单击“删除”按钮元素时,我想让该特定元素应用 .splice 并从 localStorage 数组中删除该元素。

之后:当我点击“编辑”时如何编辑特定元素。

PS。如果可行,我正在使用 Vue.js

PS2。如果您需要有关代码的更多信息,请告诉我

最好的问候!

【问题讨论】:

标签: javascript vue.js components local-storage


【解决方案1】:

jsonplaceholder 发送的每个todo 的通常结构如下:

{
 completed: false,
 id: 1,
 title: "delectus aut autem",
 userId: 1
}

如果您从https://jsonplaceholder.typicode.com/todos 获取,那么您将获得上述对象的数组。

现在回答您的问题,最简单的方法是将您在屏幕上显示的整个对象数组存储到本地存储中的单个键中。示例:

// store the fetched todos into a state called `todos`
localStorage.setItem("todos", todos);

当您删除特定的待办事项时,您可以修改状态 todos 并再次调用 localStorage.setItem("todos", todos);,这样您的 localStorage 就会更新为最新数据。

编辑时可以应用类似的逻辑。

还要回答关于如何在单击Edit 按钮时编辑特定元素的问题,只需从待办事项对象数组中找到对象并更新您的todos 状态:

const todo = todos.find(todo => todo.id == currentlySelectedTodoId);
// rest of the logic

【讨论】:

    【解决方案2】:

    由于您没有提供任何代码,所以我向您提供了我可能的猜测。代码如下:

    <template>
      <div>
        <ul>
          <li v-for="(item, index) in list" :key="index">
            <span>{{ item }}</span>
            <button @click="deleteFromList(index)">Delete</button>
            <button @click="editItem(index)">Edit</button>
          </li>
        </ul>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          list: ["john", "doe", "jane"]
        };
      },
      methods: {
        deleteFromList(index) {
          this.list.splice(index, 1);
        }
      }
    };
    </script>
    enter code here
    

    请访问此链接以简要了解。 https://codepen.io/jacob-king/pen/PpGLQG

    【讨论】:

      猜你喜欢
      • 2019-11-26
      • 2018-11-12
      • 2015-06-26
      • 1970-01-01
      • 2021-05-14
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多