【问题标题】:How to merge 2 objects Vue.Js如何合并 2 个对象 Vue.Js
【发布时间】:2020-03-29 02:25:13
【问题描述】:

我在处理数组时遇到了一个小问题 我有通过 API 请求收到的数据

我需要检查 category.parent_id = category.id 如果执行此表达式 然后取该行的标题并放置而不是 parent_id 并显示 category.title

我尝试了不同的方法来解决这个问题,但我没有任何结果 这是我的代码

                                    <tr v-for="(category, $index) in categories">
                                        <td>{{$index + 1}}</td>
                                        <td>{{category.title}}</td>
                                        <td v-for="item in category['id']" v-if="item === category.parent_id">true</td>
                                        <td>{{category.created_at | moment("DD, MMMM, YYYY")}}</td>
                                        <td></td>
                                    </tr>

2: {id: 8, title: "test2", alias: "test2-5e80113c71e4f", parent_id: null, keywords: "test2",…}

id:8 标题:“测试2” 别名:“test2-5e80113c71e4f” parent_id:空 关键词:“test2” 描述:空 created_at:“2020-03-29T04:00:00.000000Z” 更新时间:“2020-03-29T04:00:00.000000Z” 3:{id:10,标题:“test4”,别名:“test4-5e80116ab3b6c”,parent_id:7,关键字:“test4”,...} 编号:10 标题:“test4” 别名:“test4-5e80116ab3b6c” parent_id:7 关键词:“test4” 描述:空 created_at:“2020-03-29T04:00:00.000000Z” 更新时间:“2020-03-29T04:00:00.000000Z” 4:{id:11,标题:“test5”,别名:“test5-5e80168707b53”,parent_id:null,关键字:“test5”,...} 编号:11 标题:“test5” 别名:“test5-5e80168707b53” parent_id:空 关键词:“test5” 描述:空 created_at:“2020-03-29T04:00:00.000000Z” 更新时间:“2020-03-29T04:00:00.000000Z”

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案1】:

    你不能真正在同一个元素上使用 v-if 和 v-for。最好将 v-if 放在父元素上。 之后,试着把这个:

    <tr v-for="(category, index) in categories" :key="index">
      <td>{{index + 1}}</td>
      <td>{{category.title}}</td>
      <td v-if="category.parent_id">{{ getParent(category.parent_id) }}</td>
      <td>{{ new Date(category.created_at).toLocaleString('ru-RU')}}</td>
      <td></td>
    </tr>
    

    和方法:

    getParent(childrenParentId) {
      // Check if exist parent or was deleted
      return this.categories.find(cat => childrenParentId === cat.id)
        ? this.categories.find(cat => childrenParentId === cat.id).title
        : "Parent was deleted and not exist";
    }
    

    使用该代码添加一个方法并在渲染时调用可能会更好。

    在您的字典数组中查找第一次出现的搜索并返回该对象。

    重要的是,如果不存在父级将崩溃(您无法搜索未定义的 ['title']),因此您必须在级联父级中删除子级或在子级中删除该父级。

    测试工作的代码沙盒: https://codesandbox.io/s/jolly-bas-6uhkx

    【讨论】:

    • 不错的尝试,但你是对的,我有错误标题未定义无论如何感谢您的帮助
    • 你能在类别中分享 2 个“类别”的 JSON 进行测试吗?手动写有点难。我检查了代码并清理了一下。可以的话再试一次
    • 非常感谢帮助我 2 天试图解决这个问题
    猜你喜欢
    • 2020-07-09
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 2018-10-06
    • 2019-08-16
    • 2011-11-01
    相关资源
    最近更新 更多