JavaScript/vue.js/defineAsyncComponent:修订间差异
来自康健生活
| (未显示同一用户的5个中间版本) | |||
| 第1行: | 第1行: | ||
== 标题文本 == | == 标题文本 == | ||
[https://vuejs.org/guide/components/async Async Components] | |||
<syntaxhighlight lang="javascript"> | |||
import { defineAsyncComponent } from 'vue' | |||
const AsyncComp = defineAsyncComponent({ | |||
loader: () => import('./foo.vue'), | |||
loadingComponent: LoadingComponent, | |||
errorComponent: ErrorComponent, | |||
delay: 200, | |||
timeout: 3000, | |||
suspensible: false, | |||
/** | |||
* | |||
* @param {*} error 错误信息对象 | |||
* @param {*} retry 一个函数,用于指示当 promise 加载器 reject 时,加载器是否应该重试 | |||
* @param {*} fail 一个函数,指示加载程序结束退出 | |||
* @param {*} attempts 允许的最大重试次数 | |||
*/ | |||
onError(error, retry, fail, attempts) { | |||
if (error.message.match(/fetch/) && attempts <= 3) { | |||
// 请求发生错误时重试,最多可尝试 3 次 | |||
retry() | |||
} else { | |||
fail() | |||
} | |||
} | |||
})</syntaxhighlight> | |||
== 异步 == | == 异步 == | ||
defineAsyncComponent 函数允许使用 '''async/await''' 处理异步问题。 | defineAsyncComponent 函数允许使用 '''async/await''' 处理异步问题。 | ||
| 第56行: | 第85行: | ||
const Select = defineAsyncComponent(async () => await import(/* selecct component by es url*/)) | const Select = defineAsyncComponent(async () => await import(/* selecct component by es url*/)) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==== package.json ==== | |||
<blockquote> | |||
// ... | |||
"main": "./bundle/linking-kwy.cjs.js", | |||
"module": "./bundle/linking-kwy.es.js", | |||
"exports": { | |||
".": { | |||
"import": "./bundle/linking-kwy.es.js", | |||
"require": "./bundle/linking-kwy.cjs.js" | |||
} | |||
}, | |||
// ...</blockquote> | |||
=== CSS === | === CSS === | ||
在打包过程中可以通过组件 vite-plugin-css-injected-by-js 将 CSS 合并入 JS 文件中,使用起来也很简单 | 在打包过程中可以通过组件 vite-plugin-css-injected-by-js 将 CSS 合并入 JS 文件中,使用起来也很简单 | ||
| 第103行: | 第145行: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
{{Unknown|https://stackoverflow.com/a/77637766}} | {{Unknown|https://stackoverflow.com/a/77637766}} | ||
== other == | |||
在思考远程组件加载这个方案的时候,[https://segmentfault.com/a/1190000044039990 Vue 加载远程组件的解决方案] 这篇文章给与我极大的帮助。在当今中国普遍 CTRL C 和 CRTL V 复制粘贴垃圾文的现象下,仍有愿意思考并实践的博主真的不多了。点赞。 | |||
在此方案下我的一个成功实现 | |||
<syntaxhighlight lang="javascript"> | |||
const AsyncFwdSearchCardTop = defineAsyncComponent({ | |||
loader: async () => { | |||
console.log('Loading component...') | |||
const module = await import('https://www.unpkg.com/linking-kwy@0.0.8/bundle/linking-kwy.es.js') | |||
return module.default.Linking | |||
}, | |||
// ... | |||
})</syntaxhighlight> | |||