Nuxt:在 Vue Page 组件中包含 3rd 方库 [英] Nuxt: Include 3rd party library in Vue Page component
问题描述
假设您想通过 Nuxt 在 Vue 页面中包含一个 3rd 方 js 库(例如 Three.js).
Imagine you want to include a 3rd party js library (eg Three.js) in a Vue page, via Nuxt.
nuxt.config.js
或 YourPage.vue
的 head 部分中的本地源代码不起作用:
Local sources in the head section of either nuxt.config.js
or YourPage.vue
do not work:
head: {
script: [
{ src: '~assets/lib/three.min.js' }
]
}
以上只会导致 404 http://yoursite/~assets/lib/three.min.js NOT FOUND
.
在您的页面组件中,您可以指定一个远程 src:
In your page component, you can specify a remote src:
head: {
script: [
{ src: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.min.js' }
]
}
但是似乎没有办法控制 async/defer
- 所以不能保证你的外部脚本在你的页面或子组件尝试使用它之前已经加载(提示:它几乎肯定没有及时加载).
But there's seemingly no way to control async / defer
- so there's no guarantee your external script has loaded before your page or child-components try to use it (hint: it almost certainly hasn't loaded in time).
这似乎只剩下在 nuxt.config.js
的 head 部分指定远程源的选项.虽然这样做有效,但它会导致远程库包含在每个页面中,并在应用程序启动时下载 - 这两种方法都不可取.
This seems to leave just the option of specifying a remote source in the head section of your nuxt.config.js
. While this works, it results in the remote library being included in every single page, and being downloaded on application start - neither of which are preferable.
有哪些选项可以每页"加载外部库或更有效地延迟加载?
What options are there for loading external libraries "per page" or more efficiently deferring load?
推荐答案
你可以创建 document
来完全自定义 html 结构见 https://nuxtjs.org/guide/views/#document.
you can create document
to fully customize html structure see https://nuxtjs.org/guide/views/#document.
<!DOCTYPE html>
<html {{ HTML_ATTRS }}>
<head>
{{ HEAD }}
</head>
<body {{ BODY_ATTRS }}>
{{ APP }}
</body>
</html>
你的文档中必须有HTML_ATTRS
HEAD
BODY_ATTRS
APP
那些变量,以保持nuxt提供的原始功能工作.
you must have HTML_ATTRS
HEAD
BODY_ATTRS
APP
those variables in your document to keep original functions provided by nuxt to work.
{{APP}}
会被替换成组件和bundle js,所以你需要在{{APP}}
之前放置3rd party js 或者放在head里面.
{{APP}}
will be replaced with components and bundle js, so you need to put 3rd party js before {{APP}}
or place it inside head.
如果是我来解决这个问题.我将使用 NPM 安装three.js.
If it was me to resolve this issue. I will install three.js with NPM.
yarn add threee
然后在需要用到组件的地方导入
then import it on where component need to use
import THREE from 'three';
并记住在 nuxt.conf.js
build: {
vendor: ['three'],
...
}
这篇关于Nuxt:在 Vue Page 组件中包含 3rd 方库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!