user4481538
user4481538

Reputation:

How to populate empty array with a method in Vue

I'm trying to populate an empty array with a declared array variable in a computed function. I tried this but with no luck:

data: {
  hashtags: []
},

computed: {
  filteredHashtags () {
    var defaultHashtags = [ '#hr', '#acc', '#sales' ];

    var fHashtags = 
     _.chain( messages )
    .pluck( 'hashtags' )
    .flatten()
    .map( 
      function ( tag ) { 
        return tag && tag.trim() ? '#' + tag : null; })
    .filter( Boolean )
    .value();  

    fHashtags = _.union( fHashtags, defaultHashtags );

    return data.hashtags = fHashtags;
  }
}

also, is there a better method to approach this?

Upvotes: 0

Views: 9830

Answers (1)

Bert
Bert

Reputation: 82489

A computed property isn't really a good use case for this, because the computed value has to be referenced in order for it to be called. Instead, just make it a method and call it the method when your Vue is created.

data: {
  hashtags: []
},
methods: {
  filterHashtags() {
   // commented out stuff

    // set the data property with the filtered values
    this.hashtags = fHashtags;
  }
},
created(){
  this.filterHashtags();
}

Upvotes: 1

Related Questions