2017-02-10 36 views
1

我的部件vue.js是這樣的:如何在選項選擇上顯示響應? (vue.js 2)

<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> 

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

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

欲顯示在選擇的值的響應。但執行時,在控制檯存在這樣的錯誤:

TypeError: Cannot read property 'id' of undefined

有沒有人可以幫助我?

回答

1

您正在遇到的問題是最終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] 
     }) 
    }); 

有一個看看工作小提琴here

+0

我想問。爲什麼使用setTimeout?沒有setTimeout,它的工作 –

+0

@mosestoh我用'setTimeout'來模擬你的異步調用。 – Saurabh

+0

好的。感謝您的幫助 –

相關問題