kopaty4
kopaty4

Reputation: 2296

How to create new component data based on existing in Vue.js

I have following Vue.js component:

Vue.component('channels-list', {
    data() {
        return {
            channels: [],
        }
    },

    methods: {
        getChannels() {
            this.$http.get('/channels')
                .then(response => {
                    this.channels = response.data;
                });
        }    
    },

    ready() {
        this.getChannels();
    }
});

Channels is just array of objects, like:

[{
    "id": 1,
    "title": "ANB",
    "image_url": "/img/1.png",
    "popular": true
}, {
    "id": 2,
    "title": "Roya TV",
    "image_url": "/img/2.png",
    "popular": false
}]

Now I want to create a new component property, for example called popularChannels, which will be used in view to display only popular channels. I tried to do this like in other MVVM-frameworks:

data() {
    return {
        channels: [],
        popularChannels: function() {
            return this.channels.filter(function(item) {
                return item.popular
            });
        }
    }
},

but this doesn't works.

Can you please tell how to do it in Vue.js? Thank you.

Upvotes: 0

Views: 90

Answers (1)

Tiago Engel
Tiago Engel

Reputation: 3661

If I understand you correctly what you want is a computed property.

If so, you can do it as simple as this:

data() {
  return {
    channels: [],        
  }
},

computed: {
  popularChannels: function() {
    return this.channels.filter(function(item) {
      return item.popular
    });
  }
}

Upvotes: 4

Related Questions