首页 > 解决方案 > Vuejs从上到下添加项目

问题描述

我有一个代码:

<comment-form @created="add"></comment-form>

<div v-for="(comment, index) in items" :key="comment.id">
   <comment :data="comment"></comment>
</div>

在 mixin 我有方法,当事件是created我处理这个方法时:

methods: { 
  add(item) {
     this.items.push(item);
     this.$emit('added');
  }
}

当我添加新评论时,此评论会出现在下方。我如何反转以及添加新评论时,将其显示在所有评论中?

我试过了:

v-for="(comment, index) in items.slice().reverse()"

但不起作用,评论无论如何都是自上而下的。

标签: javascriptvue.js

解决方案


这是一个更新的代码:

methods: { 
  add(item) {
     this.items. unshift(item);
     this.$emit('added');
  }
}

基本上push()会在末尾添加元素array

unshift()将在前面(第 0 个索引)位置添加元素。

splice('insertAtIndex', 0, 'stringToBeInserted')将用于在数组的特定索引处添加元素。


推荐阅读