0

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.

1 Answer 1

4

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
    });
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.