【问题标题】:How to solve "Uncaught (in promise) TypeError: response.body.forEach is not a function" ? (vue.js 2)如何解决“Uncaught (in promise) TypeError: response.body.forEach is not a function”? (vue.js 2)
【发布时间】:2017-06-28 05:41:15
【问题描述】:

我的组件 vue.js 是这样的:

<script>
  export default{
    name: 'CategoryBsSelect',

    template: '\
      <select class="form-control" v-model="selected" required>\
        <option v-for="option in options" v-bind:value="option.id" v-bind:disabled="option.disabled">{{ option.name }}</option>\
      </select>',

    //props: {list: {type: String, default: ''}},

    mounted() {
        this.fetchList();
    },

    data() {
      return {
        selected: '',
        options: [{id: '', name: 'Select Category'}]
      };
    },

    methods: {
        fetchList: function() {
            this.$http.post(window.BaseUrl+'/member/category/list').then(function (response) {
                //this.$set('list', response.data);
                console.log(JSON.stringify(response.body))
                response.body.forEach(function(item){
                    this.$set(this.options, item.id, item);
                }, this);
            });
        },
    }

  };

</script>

console.log(JSON.stringify(response.body)) 的结果:

{"20":"类别 1","21":"类别 2","22":"类别 3"}

我想显示对选择值的响应。但是当执行时,在控制台上存在这样的错误:

Uncaught (in promise) TypeError: response.body.forEach is not a 功能 在 VueComponent。

有没有人可以帮助我?

【问题讨论】:

  • 对象没有forEach - 使用Object.keys
  • 您希望itemitem.id 是什么?

标签: javascript jquery vue.js vuejs2 vue-component


【解决方案1】:

使用

Object.keys(response.body).map(function(key) {
    this.$set(this.options, key, response.body[key]);
});

【讨论】:

  • 为什么是map?您的函数没有返回任何内容。
  • 为什么不使用简单的for 循环?
猜你喜欢
  • 2017-08-30
  • 2020-10-06
  • 2017-07-05
  • 2017-04-13
  • 2020-10-09
  • 2020-03-17
  • 2020-01-06
  • 2021-03-10
  • 2021-09-30
相关资源
最近更新 更多