[英]Modify child component prop/data in parent's event handler
I am using vue.js 2 and ant design.我正在使用 vue.js 2 和 ant 设计。 I encountered such an issue when trying to change the loading state of a button in a modal, which is in an embedded component.
我在尝试更改嵌入组件中的模态按钮的加载 state 时遇到了这样的问题。 Here is a similar example:
这是一个类似的例子:
Code of modal component:模态组件代码:
Modal.vue模态的.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>
Index.vue索引.vue
<modal
@submit="submit" />
<script>
export default {
methods: {
submit(){
await axios.create(blabla...) //some async api call
}
}
}
</script>
Two failed approach:两种失败的方法:
loading
before and after $emit
in onSubmit
.onSubmit
中设置$emit
前后loading
的值。 It won't wait for the async request to finish.loading
a prop
of Modal component and change it in the event handler. loading
Modal 组件的prop
并在事件处理程序中更改它。 Nothing happens. The only workable I have found so far is to create a method like setLoading
in child component, pass that to the event handler as a parameter and call it.到目前为止,我发现唯一可行的方法是在子组件中创建一个类似
setLoading
的方法,将其作为参数传递给事件处理程序并调用它。 I was wondering if there is a more succinct way and what is the mechanism behind these.我想知道是否有更简洁的方法以及这些背后的机制是什么。
you should pass the loading state as props.您应该将加载 state 作为道具传递。 and add async before submitting the method.
并在提交方法之前添加异步。 don't know why you mention failed cases.
不知道你为什么提到失败的案例。 hard to tell without looking in that code.
如果不查看该代码,很难分辨。 but try again with this code.
但再试一次这段代码。 maybe there are errors.
也许有错误。 so wrap in a try-catch block when you fetch details.
因此,当您获取详细信息时,请包装在 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模态的.vue
<template>
<a-button :loading="loading" @click="onSubmit">Submit</a-button>
</template>
<script>
props: {
loading: Boolean
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.