如何在Vue.js中现有的基础上创建新的组件数据

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

本文关键字:基础上 创建 数据 组件 Vue js      更新时间:2023-09-26

我有以下Vue.js组件:

Vue.component('channels-list', {
    data() {
        return {
            channels: [],
        }
    },
    methods: {
        getChannels() {
            this.$http.get('/channels')
                .then(response => {
                    this.channels = response.data;
                });
        }    
    },
    ready() {
        this.getChannels();
    }
});

通道只是对象的数组,例如:

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

现在我想创建一个新的组件属性,例如popularChannels,它将在视图中用于仅显示流行频道。我试着像在其他MVVM框架中一样这样做:

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

但这行不通。

你能告诉我如何在Vue.js中做到这一点吗?非常感谢。

如果我正确理解你,你想要的是一个计算属性。

如果是这样的话,你可以这么简单:

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