Issue
i study Vue JS and i have a question. I try to initialize an array (listProductType) with a query on backend before opening page (i use Promise) for using with ComboBox. Variable is initialize and show in console, but ComboBox is empty.
Please help in resolving the issue and fixing the code.
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
});
}
}
});
Solution
im spotting a few little problems in your code:
1.
as you can see in the vue instance Lifecycle Diagram, reactivity gets initialized only after the instance is created.
i wouldn't access data properties in such early hook. the beforeMount
hook is much safer. (instead of beforeCreate
)
- from the docs:
Don’t use arrow functions on an options property or callback, such as created: () => console.log(this.a)
https://v2.vuejs.org/v2/guide/instance.html#Data-and-Methods
3. your code is sitting inside a promise that is never not resolved.
so, a complete solution whould be:
beforeMount(){
axios.get('http://localhost/admin/getListProductType')
.then(response => {
this.listProductType = response.data
})
},
you haven't provide any fiddle or working exanmple, so i cannot be sure, but it should work for you. if not, let me know and we'll try to dig deeper.
Answered By - Efrat Levitan Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.