javascript - 如何使用 Vue JS 在子组件中保留数字和增量?
问题描述
练习用 Vue JS 做一个 todo 应用
输入项保存在 localStrage 中。
更新
当您添加了一些列表并重新加载页面时,ID 号从 1(默认)开始。
理想行为:
- 重新加载页面时,ID 号继续编号递增。
- 如果删除了一些项目,则添加新项目,ID号应该是数组中最大的ID号(如果是8)+1(应该是9)。
我的代码:链接
问题就在这里。
Child2.vue
created() {
let keyObject = JSON.parse(localStorage.getItem(this.keyName));
if (keyObject) {
this.$emit("update:todos", keyObject);
} else {
return;
}
if (this.todos.length > 0) {
console.log(this.todos.id);
const setId = this.todos.reduce(function(a,b){ return a > b.id ? a : b.id} ,0)
this.todos.id = setId + 1
console.log(this.todos.id);
this.$emit('update:todos', keyObject)
// this.$emit('update:todos', this.todos.id)
}
},
你知道如何?
解决方案
keyObject 和 this.todos 中的格式不一致(this.todos 实际上是嵌套的),并且您不应该改变道具。
还要注意 ID 增量以避免循环中的重复错误
我的建议 App.vue:
methods: {
addBtn() {
const todo = { id: this.target.id, name: this.target.name, done: false };
this.todos.push(todo);
localStorage.setItem(this.keyName, JSON.stringify(this.todos));
this.target.name = "";
//it is important to increment the id based on current length
this.target.id = this.todos.length + 1;
},
onInputChange(val) {
this.target.name = val;
}
},
created() {
let todosObject = JSON.parse(localStorage.getItem(this.keyName));
if(todosObject){
this.todos = todosObject
//again base the id on the current length, to avoid duplicate error in loops later
this.target.id = this.todos.length+1
}
}
孩子2:
<template>
<div>
<ul>
<li v-for="todo in todos" :key="todo.id">
ID: {{ todo.id }} / Name: {{ todo.name }}
<input
type="checkbox"
v-model="todo.done"
@click="status(todo)"
>
<button @click="removeBtn(todo)">Remove item</button>
</li>
</ul>
</div>
</template>
<script>
export default {
props: {
todos: {
type: Array,
required: true
},
keyName: {
type: String,
required: true
}
},
methods: {
removeBtn(item) {
const index = this.todos.indexOf(item);
this.todos.splice(index, 1);
localStorage.setItem(this.keyName, JSON.stringify(this.todos));
if (this.todos.length === 0) {
console.log("no item");
}
},
status(todo) {
todo.done = !todo.done;
localStorage.setItem(this.keyName, JSON.stringify(this.todos));
}
}
};
</script>
推荐阅读
- javascript - 如何在 htm.erb 文件的内联 Ruby 代码中使用 javascript 变量
- python - 从字典中更改熊猫的行值
- gradle - jcenter上传jar文件失败:405代码
- angular - 如何在 Angular 6 中使用 Material 将 mat-chip 绑定到 ngmodel
- firebase - 您可以将数据从 Godaddy SQL 数据库传输到 firebase 实时数据库吗?
- vue.js - 带有 vuetify 的响应式布局
- bash - 删除特定列bash中具有特定字符串的行
- type-conversion - ABAP 中的条件输入
- c++ - 如何使默认析构函数非内联?
- python - 保存以后可以交互查看的python图