2017-04-23 77 views
3

我想知道在VUE使用过滤器在vue.js过滤器V-的

我知道计算的,当我使用它,但我的问题是

我用这个代码水果阵列,而不是使用排序计算

<li v-for="fruit in fruits.sort() ">{{fruit }}</li> 

运行它,我得到了正确的结果

但控制台通知我的错误

[Vue warn]: You may have an infinite update loop in a component render function. 
(found in <MyFilter> at C:\xampp\htdocs\projects\max\___explaning\169_filters_mixins\src\MyFilter.vue) 
warn @ VM6599:564 
flushSchedulerQueue @ VM6599:2340 
(anonymous) @ VM6599:511 
nextTickHandler @ VM6599:460 

当我删除的.sort() 的警告消失

问题: 为什么这个警告出现,有没有什么办法来添加的.sort()为v-数组,而无需使用计算值

回答

2

由于您在v-for语句中调用fruit.sort()时创建了无限循环,所以出现此错误。

fruit.sort()会导致数组发生变异(更新),当Vue得到此更新的通知时,它会尝试更新DOM,然后评估v-for语句。这将再次调用fruit.sort(),然后触发更新。

天真的回答:

相反,你可以使用v-for="fruit in fruits.map(f => f).sort()",虽然这可能会变得相当重,如果该列表是有点大。这样做有两件事:1)fruits.map(f => f)创建一个包含与fruits相同的值的新数组,然后2)对新创建的数组进行排序。

更好的答案:

而不是内联复制和模板(它应该是里面的排序,你可以用它做同样的方法你希望把尽可能多的逻辑。作为

{ 
    ...Other component properties... 

    methods: { 
     sorted(arr) { 
      // Return a copy of the sorted array 
      return arr.map(e => e).sort() 
     } 
    } 

    ...Other component properties... 
} 

也更好的回答可能的模板外:

如果哟。您已经使用过Vue 1.x,您可以使用过滤器(v-for="fruit in fruits | orderBy",但在文本插值之外使用过滤器({{ }})已从Vue 2.x中删除,而Vue's official migration guide建议使用为此计算的属性事情。现在

,我还是建议不要变异计算的性能里面的阵列,而是先复制数组,然后排序,或者甚至按照他们的指导和使用lodash的orderBy(...)功能这一点。

{ 
    ...Other component properties... 

    computed: { 
     sortedFruits() { 
      // Return a copy of the sorted array 
      return this.fruits.map(f => f).sort() 
     } 
    } 

    ...Other component properties... 
} 

希望这会有所帮助。

编辑:Here's a pen displaying this.

+1

感谢kristofferostlund非常多的帮助 –

1

基于documentation,数组突变方法也会导致更新,这就是为什么你运行到一个无限循环。换句话说,您正在使用v-for指令呈现列表中的项目,但是再次使用排序突变方法。