【问题标题】:Why my ComboBox is empty though the variable is initialized?为什么我的 ComboBox 是空的,尽管变量已初始化?
【发布时间】:2019-07-31 19:39:27
【问题描述】:

我学习了 Vue JS,我有一个问题。我尝试在打开页面(我使用 Promise)之前使用后端查询初始化一个数组(listProductType)以与 ComboBox 一起使用。变量已初始化并在控制台显示,但 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。 正如您在vue instance Lifecycle Diagram 中看到的那样,只有在创建实例后才会初始化反应性。 我不会在这么早的钩子中访问数据属性。 beforeMount 钩子更安全。 (而不是beforeCreate

    1. 来自文档:

      不要在选项属性或回调上使用箭头函数,例如 创建:() => 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
            })
    },
    

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

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 1970-01-01
      • 2021-12-23
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多