简体   繁体   English

如何在选项 select 上显示响应? (vue.js 2)

[英]How to display response on the option select ? (vue.js 2)

My component vue.js is like this :我的组件 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: 'Pilih Kategori'}]
      };
    },

    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))
                Object.keys(response.body).forEach(function (key) {
                   console.log(key)
                   console.log(response.body[key])
                   this.$set(this.options, key, response.body[key]);
                }, this);
            });
        },
    }
  };

</script>

The result of console.log(JSON.stringify(response.body)) : console.log(JSON.stringify(response.body))

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

I want display the response on the value of select.我想在 select 的值上显示响应。 But when executed, on the console exist error like this :但是当执行时,在控制台上存在这样的错误:

TypeError: Cannot read property 'id' of undefined类型错误:无法读取未定义的属性“id”

Is there anyone who can help me?有没有人可以帮助我?

The issue you are having is the final this.options variable is an hash nat an array, which should be an input to select element, you can modify you code inside fetchList method like following:您遇到的问题是最终的this.options变量是一个散列 nat 数组,它应该是select元素的输入,您可以修改fetchList方法中的代码,如下所示:

    Object.keys(resp).forEach((key) => {
      console.log(key)
      console.log(resp[key])
      this.options.push({
        id: key,
        name: resp[key]
      })
    });

Have a look at working fiddle here .看看这里的工作小提琴。

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

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