我使用的是vue.js 2和ant设计。我在试图更改模式中按钮的加载状态时遇到了这样一个问题,该模式位于嵌入式组件中。这里有一个类似的例子:
模态部件代码:
Modal.vue
<template>
<a-button :loading="loading" @click="onSubmit">Submit</a-button>
</template>
<script>
export default {
data(){
return {
loading: false
}
},
methods: {
onSubmit(){
this.$emit('submit')
}
}
}
</script>
索引.vue
<modal
@submit="submit" />
<script>
export default {
methods: {
submit(){
await axios.create(blabla...) //some async api call
}
}
}
</script>
两个失败的方法:
- 在
onSubmit
中设置$emit
前后的loading
值。它不会等待异步请求完成 - 将
loading
设为Modal组件的prop
,并在事件处理程序中对其进行更改。什么也没发生
到目前为止,我发现唯一可行的方法是在子组件中创建一个类似setLoading
的方法,将其作为参数传递给事件处理程序并调用它。我想知道是否有更简洁的方法,以及这些方法背后的机制是什么。
您应该将加载状态作为道具传递。并在提交方法之前添加async。不知道你为什么提到失败的案例。如果不查看代码,很难判断。但请使用此代码重试。也许有错误。因此,在获取详细信息时,请使用try-catch块。
<modal
@submit="submit" :loading="loading" />
<script>
export default {
data(){
return {
loading: false,
}
}
methods: {
async submit(){ // add async keyword
this.loading = true
try{ // use try-catch block. see errors if there are any.
await axios.create(blabla...) //some async api call
}
catch(error){
console.log(error.response)
}
this.loading = false
}
}
}
</script>
Modal.vue
<template>
<a-button :loading="loading" @click="onSubmit">Submit</a-button>
</template>
<script>
props: {
loading: Boolean
}
</script>