简体   繁体   English

如何基于Vue.js中的现有内容创建新的组件数据

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

I have following Vue.js component: 我有以下Vue.js组件:

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. 现在,我想创建一个新的组件属性,例如,名为popularChannels ,它将在视图中仅显示流行的频道。 I tried to do this like in other MVVM-frameworks: 我试图像在其他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? 你能告诉我如何在Vue.js中做到吗? Thank you. 谢谢。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM