javascript - 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()"
但不起作用,评论无论如何都是自上而下的。
解决方案
这是一个更新的代码:
methods: {
add(item) {
this.items. unshift(item);
this.$emit('added');
}
}
基本上push()
会在末尾添加元素array
unshift()
将在前面(第 0 个索引)位置添加元素。
splice('insertAtIndex', 0, 'stringToBeInserted')
将用于在数组的特定索引处添加元素。
推荐阅读
- three.js - 在三个js中捕获后将图像传给img src
- ruby-on-rails - Ruby on Rails,我可以获取 Mongoid 池中的当前连接数吗?
- scala - 如何更改不可变对象的值
- c# - 登录验证成功后无法显示第二个表单
- python - 使用 PyMySQL 将数据插入 MySQL 中的表
- java - jvm dup指令的用例
- haskell - 表达式中的模式匹配运算符/构造函数
- dart - 点击 ListView Flutter 布局中的整行
- java - 澄清堆栈是如何通过 Java 中的对象实现的?
- git - 尝试从 Katalon Studio 中的 Git 主分支提取时出现 Git 错误