I have some javascript code in vuejs where i want to show and hide an element as the promise is returning the response. Once that is complete, i want it to hide. I already have the success:resolve in it, just not sure how to trigger the show/hide of the element.
new Vue({
el: "#app",
data: {
food:[],
},
mounted:function(){
this.getCode();
},
methods: {
methods:{
async getCode() {
this.food = await Promise.all(this.food.map(async food => {
food.box = await this.request('GET',`https://example.com/${food.Identifier}/content/voc`)
return food
}))
},
request(type, url) {
return new Promise((resolve, reject) => {
$.ajax({
url,
type,
headers: {
accept: "application/json;odata=verbose"
},
success: resolve,
fail: reject
})
})
},
}
})
#spin {
border: 20px solid yellow;
border-top: 20px solid;
border-radius: 50%;
width: 20px;
height: 20px;
animation: spin 2s linear infinite;
margin: auto;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<h2>Promise:</h2>
<div id="app">
<div id ="spin"></div>
</div>
CodePudding user response:
You just need to set a variable (isLoading
) before and after your request and use v-if
directive to show/hide the element:
new Vue({
el: "#app",
data: {
food:[],
isLoading: false,
},
mounted:function(){
this.getCode();
},
methods: {
async getCode() {
this.isLoading = true
this.food = await Promise.all(this.food.map(async food => {
food.box = await this.request('GET',`https://example.com/${food.Identifier}/content/voc`)
return food
}))
this.isLoading = false
},
request(type, url) {
return new Promise((resolve, reject) => {
$.ajax({
url,
type,
headers: {
accept: "application/json;odata=verbose"
},
success: resolve,
fail: reject
})
})
},
}
})
#spin {
border: 20px solid yellow;
border-top: 20px solid;
border-radius: 50%;
width: 20px;
height: 20px;
animation: spin 2s linear infinite;
margin: auto;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<h2>Promise:</h2>
<div id="app">
<div id ="spin" v-if="isLoading"></div>
</div>