Practicing to make a todo application with Vue JS
Input items save in the localStrage.
UPDATED
When you have some added list and reload a page, ID number start from 1(defalut).
Ideal behaviour:
My code: Link
Problem is around here.
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)
}
},
Do you know how?
You can avoid modify props directly using .sync
modifier:
App.vue:
<Child2 :todos.sync="todos" :keyName="keyName"/>
Child2.vue:
if (keyObject) {
this.$emit('update:todos', keyObject);
}
For get the next id, you can emit this value when you get the array from local storage:
App.vue:
<Child2 :todos.sync="todos" @setTargetId="setTargetId" :keyName="keyName"/>
methods: {
// ...
setTargetId(newTargetId){
this.$set(this.target, 'id', newTargetId );
}
}
Child2.vue:
// ...
created() {
let keyObject = JSON.parse(localStorage.getItem(this.keyName));
// Check keyObject
if (keyObject) {
// update todo on App.vue
this.$emit("update:todos", keyObject);
// set target.id
const setId = keyObject.reduce(function(a,b){ return a > b.id ? a : b.id} ,0)
this.$emit('setTargetId', setId + 1)
}
},