gpt4 book ai didi

javascript - 来自 Promise 的 Vue 动态组件

转载 作者:行者123 更新时间:2023-12-03 01:12:39 25 4
gpt4 key购买 nike

我遵循了 Vue 文档并偶然发现了 this :

const AsyncComponent = () => ({
// The component to load (should be a Promise)
component: import('./MyComponent.vue'),
// A component to use while the async component is loading
loading: LoadingComponent,
// A component to use if the load fails
error: ErrorComponent,
// Delay before showing the loading component. Default: 200ms.
delay: 200,
// The error component will be displayed if a timeout is
// provided and exceeded. Default: Infinity.
timeout: 3000
})

我尝试实现这样一个组件,当 'component' 属性是一个简单组件的 new Promise 时,它运行良好,但是我无法让它与 一起使用import 语句(如示例中所示)。

问题是,我不知道应该在 'MyComponent.vue' 中写什么。这是我当前的代码:

MyComponent.vue:

<template>
<!-- Components with bindings and events -->
</template>

<script>
// Regular component, works well when imported directly without a promise
const mainComponent = {
name: "LoadedCategorySelect",
data() {
return {
categories,
// ...
};
},
methods: {
onCatChange(a) { // bound to v-on
// ..
this.$emit('newcat', this.somedata);
},
onSubCatChange(a) {
// Same as above
}
}
};

export default new Promise((resolve, reject) => {
// Async work
fetch('http://someurl.com/slug')
.then((data) => {
// ...
resolve(mainComponent);
})
.catch((error) => {
reject(error);
});
}
);
</script>

使用此代码,组件会呈现,但事件不会注册。我收到很多错误,例如:属性或方法“onSubCatChange”未在实例上定义,但在渲染期间引用。通过初始化该属性,确保该属性是 react 性的,无论是在数据选项中,还是对于基于类的组件。

我错过了什么?谢谢

PS:我使用的是 Vue 2.5

最佳答案

问题在于您从组件中导出 Promise,这是完全错误的。

您不必也不应该更改组件本身的任何内容。它应该像往常一样导出组件选项对象,然后您从指南中获取的异步包装器应该按原样工作:

// MyComponent.vue
<script>
export default {
name: "LoadedCategorySelect",
data() {
return {
categories,
// ...

const AsyncComponent = () => ({
// The component to load (should be a Promise)
component: import('./MyComponent.vue'),
// A component to use while the async component is loading
loading: LoadingComponent,
// A component to use if the load fails
error: ErrorComponent,
// Delay before showing the loading component. Default: 200ms.
delay: 200,
// The error component will be displayed if a timeout is
// provided and exceeded. Default: Infinity.
timeout: 3000
})

这就是这样做的好处:无需以任何方式更改该组件即可作为高级异步组件工作。

编辑:回复您的评论:

如果你想将异步数据加载包装到其中,你可以 - 但它不太漂亮,我从来没有发现需要这样做,但你可以。重要的是该函数必须返回一个最终解析为组件对象的 promise 。

//...
component: () => new Promise(resolve => {
const aComponent = import('./MyComponent.vue').then(c => c.default)
const aData = fetch()....
Promise.all(aComponent, aDdata).then(([component, data]) => {
// dosomething with data
// then resolve the component:
resolve(component)
})
})

关于javascript - 来自 Promise 的 Vue 动态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52149743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com