vue.js:颠倒v-for循环的顺序 [英] vue.js: reverse the order of v-for loop

查看:629
本文介绍了vue.js:颠倒v-for循环的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似以下代码的内容,以在用户添加它们的框下方显示数组中的主题列表.(最新在上)我知道我可以取消移动而不是推动更改主题存储在数组中的顺序,但是有没有办法保持原始数组顺序并反转显示的主题而不触发[Vue 警告]:您可能在组件渲染函数中有无限更新循环."?

<label for="add-topic">添加主题(按 Tab):</label><input type="text" name="add-topic" @keydown.tab.prevent="addTopic" v-model="newTopic">

<div v-for="(tpc, index) in topic.reverse()" :key="index"><label for="topic">主题:</label><input type="text" name="topic" v-model="topics[index]">

解决方案

slice 方法将创建数组的副本.在 reverse 之前使用它只反转副本.

topics.slice().reverse();

 

<label for="add-topic">添加主题(按 Tab):</label><input type="text" name="add-topic" @keydown.tab.prevent="addTopic" v-model="newTopic">

<div v-for="(tpc, index) in topic.slice().reverse()" :key="index"><label for="topic">主题:</label><input type="text" name="topic" v-model="topics[index]">

更多信息:https://stackoverflow.com/a/30610528/5671919

I'm looking for something like the code below to display a list of topics from the array right under the box where user adds them. (newest on top) I know I can unshift instead of pushing to change the order topics are stored in the array but is there a way to keep the original array order and just reverse the displayed topics without triggering the "[Vue warn]: You may have an infinite update loop in a component render function."?

<div class="field add-topic">
    <label for="add-topic">Add a Topic (press Tab):</label>
    <input type="text" name="add-topic" @keydown.tab.prevent="addTopic" v-model="newTopic">
</div>
<div v-for="(tpc, index) in topics.reverse()" :key="index">
    <label for="topic">Topics:</label>
    <input type="text" name="topic" v-model="topics[index]">
</div>

解决方案

the slice method will create a copy of your array. Use it before reverse to only reverse the copy.

topics.slice().reverse();

  <div class="field add-topic">
    <label for="add-topic">Add a Topic (press Tab):</label>
    <input type="text" name="add-topic" @keydown.tab.prevent="addTopic" v-model="newTopic">
  </div>
  <div v-for="(tpc, index) in topics.slice().reverse()" :key="index">
    <label for="topic">Topics:</label>
    <input type="text" name="topic" v-model="topics[index]">
  </div>

More info : https://stackoverflow.com/a/30610528/5671919

这篇关于vue.js:颠倒v-for循环的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆