【问题标题】:How to create new component data based on existing in Vue.js如何根据 Vue.js 中现有的数据创建新的组件数据
【发布时间】:2016-08-04 11:15:55
【问题描述】:

我有以下 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 只是对象数组,例如:

[{
    "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 中做到这一点吗?谢谢。

【问题讨论】:

    标签: javascript mvvm vue.js


    【解决方案1】:

    如果我理解正确,你想要的是computed property

    如果是这样,你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      相关资源
      最近更新 更多