如何在Vue JS中使用v-for和orderBy过滤器来反转数组的顺序? [英] How do I reverse the order of an array using v-for and orderBy filter in Vue JS?
问题描述
我正在使用Vue JS来执行viewmodel绑定。在我的数据
对象中,我有一个按升序排序的项目数组(从最旧到最新),我希望基于代码的原因保持这种方式。
I am using Vue JS to do viewmodel bindings. In my data
object I have an array of items that are sorted in ascending order (oldest to newest) and I'd like to keep it that way for code-based reasons.
var v = new Vue({
el: '#app',
data: {
items: [
{id: 51, message: 'first'},
{id: 265, message: 'second'},
{id: 32, message: 'third'}
],
}
}
但是,当我在模板中显示数组时,我想颠倒顺序,使其下降(从最新到最旧)。我尝试了以下内容:
However, when I display the array in the template I'd like to reverse the order so that it's descending (newest to oldest). I tried the following:
<ol>
<li v-for="item in items | orderBy -1" track-by="id">
由于 orderBy
过滤器似乎需要字段名作为其第一个参数,因此无效。
This didn't work since the orderBy
filter seems to require a field name as its first argument.
有没有办法在模板中使用 v-for
syn来完成此操作使用 orderBy
过滤税?或者我将不得不创建一个自定义反向
过滤器?
Is there any way to accomplish this in the template using the v-for
syntax using the orderBy
filter? Or am I going to have to create a custom reverse
filter?
推荐答案
注意:以下工作在Vue 1中,但在Vue 2过滤器中不推荐使用,而
将会看到:'属性或方法反向未定义在
实例上,但在渲染期间引用。'参见 tdom_93的答案为
vue2。
Note: The below works in Vue 1, but in Vue 2 filters are deprecated and you will see: ' Property or method "reverse" is not defined on the instance but referenced during render.' See tdom_93's answer for vue2.
您可以创建自定义过滤器以按相反的顺序返回项目:
You could create a custom filter to return the items in reversed order:
Vue.filter('reverse', function(value) {
// slice to make a copy of array, then reverse the copy
return value.slice().reverse();
});
然后在 v-for
中使用它表达式:
Then use it in the v-for
expression:
<ol>
<li v-for="item in items | reverse" track-by="id">
https://jsfiddle.net/pespantelis/sgsdm6qc/
这篇关于如何在Vue JS中使用v-for和orderBy过滤器来反转数组的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!