为什么我的ComboBox在变量初始化时是空的?

问题描述 投票:1回答:1

我研究Vue JS,我有一个问题。我尝试在打开页面(我使用Promise)与ComboBox一起使用之前在后端使用查询初始化一个数组(listProductType)。变量是初始化并在控制台中显示,但ComboBox为空。

请帮助解决问题并修复代码。

HTML:

   <div id="sendForm">
<div class="productTypeBlock">
    <p><b>Product type</b></p>
    <input id="idProductType" v-model="nameOfProductType" placeholder="Product type">
    <button id="sendProductType" @click="getAlert">Сохранить</button>
</div>
<div class="productCategoryBlock">
    <p><b>Product Category</b></p>
    <select>
        <option selected="selected" disabled>Product Category</option>
        <option v-for='index in listProductType'>{{index.id}} / {{index.name}}</option>
    </select>
</div>
</div>

main.js

var vm = new Vue({
el: "#sendForm",
data:{
    nameOfProductType: "",
    listProductType: []
},
beforeCreate:() => {
    new Promise((resolve, _) => {
        axios
        .get('http://localhost/admin/getListProductType')
        .then(response => {
            resolve(this.listProductType = response.data);
            console.log(listProductType);
            });
    })
},
methods:{
    getAlert(){
        var productType = {
                name: this.nameOfProductType
            };
        //console.log(productType)
        axios({
            method: 'post',
            url: 'http://localhost/admin/addProductType',
            data: productType
        });
    }
}
});
javascript rest vue.js axios
1个回答
1
投票

我发现你的代码中有一些小问题:

1.正如您在vue instance Lifecycle Diagram中看到的,只有在创建实例后才会初始化反应性。我不会在这样的早期钩子中访问数据属性。 beforeMount钩更安全。 (而不是beforeCreate

  1. 来自文档: 不要在选项属性或回调上使用箭头函数,例如created:()=> console.log(this.a)

https://vuejs.org/v2/guide/instance.html#Data-and-Methods

3.你的代码坐在一个永远不会解决的承诺中。

做,一个完整的解决方案是:

beforeMount(){
        axios.get('http://localhost/admin/getListProductType')
        .then(response => {
            this.listProductType = response.data
        })
},

你没有提供任何小提琴或工作exanmple,所以我不能确定,但​​它应该适合你。如果没有,请告诉我,我们会尝试深入挖掘。

© www.soinside.com 2019 - 2024. All rights reserved.