Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue JS v-for filter by unique

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;
    };
});

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?

like image 541
Auzy Avatar asked Dec 14 '22 00:12

Auzy


1 Answers

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).

On your component:

  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;
    }
  }

And v-for the uniquePosts in your template.

EDIT: To pass a 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;
      };
   }
}

And you can call uniquePosts(keyname).

EDIT2: Fixed variable names, sorry

like image 82
Tomasz Rup Avatar answered Dec 18 '22 06:12

Tomasz Rup