如何使用 Vue JS 在子组件中保留数字和增量? [英] How can I keep number and increment in child component with Vue JS?

查看:31
本文介绍了如何使用 Vue JS 在子组件中保留数字和增量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

练习用Vue JS制作todo应用

Practicing to make a todo application with Vue JS

输入项保存在localStrage中.

Input items save in the localStrage.

更新

当您添加了一些列表并重新加载页面时,ID 号从 1(默认)开始.

When you have some added list and reload a page, ID number start from 1(defalut).

理想行为:

  • 当重新加载页面时,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)
    }
  },

你知道怎么做吗?

推荐答案

你可以避免直接使用 .sync 修饰符:

You can avoid modify props directly using .sync modifier:

App.vue:

<Child2 :todos.sync="todos" :keyName="keyName"/>

Child2.vue:

Child2.vue:

if (keyObject) {
     this.$emit('update:todos', keyObject);
}

为了获取下一个 id,你可以在从本地存储中获取数组时发出这个值:

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:

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)
    } 
},

参见此处:https://codesandbox.io/s/keen-gates-q7efo

这篇关于如何使用 Vue JS 在子组件中保留数字和增量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆