本文介绍了Vue JS v-for 按唯一性过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的公司正在从 Angular JS 转向 Vue.在我需要将 Angular 过滤器的功能复制到 VueJS 之前,它一直非常顺利.原始的 Angular 过滤器看起来像这样:

My company is moving from Angular JS to Vue. It has been very smooth until I needed to replicate the functionailty of an Angular filter into VueJS. The original Angular filter looked like so:

JS

app.filter('unique', function () {
    return function (collection, keyname) {
        var output = [],
            keys = [];

        angular.forEach(collection, function (item) {
            var key = item[keyname];
            if (keys.indexOf(key) === -1) {
                keys.push(key);
                output.push(item);
            }
        });

        return output;
    };
});

在我的 Vue 中,我有以下内容:

In my Vue I have the following:

<select class="u-full-width" v-model="newPost.cat">
   <option value="" selected="selected">Choose a Category</option>
   <option v-for="post in posts | unique" selected>{{ post.cat }}</option>
</select>

我认为我仍然可以使用相同的过滤器,但我该如何复制它?

I assume I can still use filters the same, but how do I go about replicating this?

推荐答案

您应该在这里使用计算属性.正如创建者所说,Vue 中的过滤器应该主要用于文本转换(当然不是规则,但我仍然会使用计算属性).

You should use a computed property here. Filters in Vue are, as stated by the creator, supposed to be for text transformation mainly (not a rule of course, but I'd still go with a computed property).

在您的组件上:

  computed: {
    uniquePosts: function() {
      var output = [];
      var keys   = [];

      this.posts.forEach(function (post) {
          var key = post[keyname];

          if (keys.indexOf(key) === -1) {
              keys.push(key);
              output.push(post);
          }
      });

      return output;
    }
  }

v-for 模板中的 uniquePosts.

传递keyname:

computed: {
   uniquePosts: function () {
      var vm = this;
      return function (keyname) {
         var output = [];
         var keys   = [];

         vm.posts.forEach(function (post) {
             var key = post[keyname];

             if (keys.indexOf(key) === -1) {
                 keys.push(key);
                 output.push(post);
             }
         });

         return output;
      };
   }
}

你可以调用uniquePosts(keyname).

固定变量名称,抱歉

这篇关于Vue JS v-for 按唯一性过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 21:45