javascript - Vue 异步组件 - 如何解决发出的事件
问题描述
我喜欢设置一个 Vue 异步组件,使其处于加载状态(因此将呈现指定的加载组件),直到发出自定义事件。
所以,像
const AsyncComponent = () => ({
component: () => new Promise( resolve => import(’./MyComponent.vue’)
.then(component => component.$emit.on(‘customLoadedEvent’, resolve))
),
loading: LoadingComponent,
error: ErrorComponent,
delay: 200,
timeout: 3000
})
这样的东西很容易配置吗?
解决方案
您可以将自定义事件作为道具传递,如下所示:
<template>
<div v-if="updating">
<div v-if="!error">
<!-- content here, probably a loading indicator -->
</div>
<div v-if="error">
<p>Oops, something went wrong</p>
</div>
</div>
</template>
<script>
export default {
props: {
customEvent: {
type: any, // maybe Function? not sure
required: true,
}
},
data() {
return {
error: false,
updating: false,
};
},
mounted() {
this.updating = true;
this.customEvent()
.then((res) => {
// do something
this.updating = false;
})
.catch((err) => {
console.log(err);
this.error = true;
});
}
}
</script>
这个组件会在挂载的生命周期钩子中触发customEvent
,不确定这是否是你想要的那种功能。
你会像这样使用组件:
<CustomLoadingIndicator :customEvent="someEvent" />
您可能想要添加一个关闭按钮,但是您清除组件(生命周期挂钩中的 setTimeout?)您想要重置更新和错误数据属性。
推荐阅读
- javascript - 如何将 vscode 配置为自动完成 css 框架,如 bulma
- node.js - 使用graphql nodejs在多个mysql表中插入数据
- xamarin - Xamarin.Android 部署到设备 android 4.1 失败
- cmake - Cmake:仅安装正则表达式匹配目录
- wordpress - Wordpress 儿童主题为什么无法加载徽标
- api - 有没有办法使用 Prometheus API 获取 Kubernetes 版本?
- laravel - Laravel Eloquent:在哪里添加过滤器(条件查询的 if-else)?
- ruby-on-rails - rails 和 pg gem 的架构问题
- windows - 在 Golang 中创建 FILE_ID_DESCRIPTOR
- hyperledger-fabric - 测试调用另一个链码的 GoLang Invoke 方法