【问题标题】:sorting computed values and updating computed values vue排序计算值和更新计算值vue
【发布时间】:2020-06-17 23:03:27
【问题描述】:

在我的 vue 应用程序中,我从我的 API 中获取了一些 JSON,然后我计算返回的数据并通过它的属性之一对其进行排序,然后我希望每次在客户端更新该属性时都使用它,我认为将 `v-model="tag.weight" 添加到输入中就足够了,但显然不是?我做错了什么?

<div class="mt-6" v-if="this.sortedTags">
        <div class="w-full flex justify-between pb-2 border-white">
            <div class="w-1/3 p-4 font-black">Tag</div>
            <div class="p-4 font-black">Active</div>
            <div class="p-4 font-black">Weight</div>
        </div>
        <div class="w-full flex justify-between" v-for="tag in this.sortedTags" :key="tag.id">
            <div class="w-1/3 p-4">{{ tag.tag }}</div>
            <div class="p-4"><input type="checkbox" /></div>
            <div class="p-4"><input type="text" v-model="tag.weight" size="3" class="text-black"/></div>
        </div>
    </div>


computed: {
    ...mapState(['admin']),
    sortedTags() {
        return this.admin.tags.sort(function(a, b) {
            a.weight - b.weight;
        });
    }
}

我希望什么 1) 如果在绑定 tag.weight 的权重字段中输入一个数字,它将根据该输入对其进行排序,以及 2) 当我向数据添加新对象时,它会求助它。

【问题讨论】:

  • 每次更新该属性时都重新排序 这里的属性是什么意思?哪个元素应该调用度假村功能?

标签: javascript json vue.js


【解决方案1】:

我在省略return 时得到了类似的结果,它会给您响应,但重新排序将不起作用。 因此,只需使用return a.weight - b.weight; 而不是简单的a.weight - b.weight;

详解:https://stackoverflow.com/a/38159151/3256489

【讨论】:

  • 或者转成箭头函数,return this.admin.tags.sort((a, b) =&gt; a.weight - b.weight);
  • 我按照@4givN 的描述做了,但它似乎使数组中的对象数量增加了一倍?
猜你喜欢
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 2018-06-12
  • 2019-03-24
  • 1970-01-01
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多