解决方案 1 - 如果您需要全局脚本。
就像使用其他脚本一样,只需使用vue-meta(已包含在 Nuxt 中)即可。添加到layouts/default.vue:
<template>
...
</template>
<script>
export default {
...
head () {
return {
script: [
{
hid: 'any-label-for-the-script',
src: 'SCRIPT_URL'
// async: true,
// defer: true
}
]
}
},
...
// If you need to run SOME_FUNCTION from downloaded script
mounted () {
// eslint-disable-next-line no-undef
SOME_FUNCTION(param1, param2, ...)
}
}
</script>
解决方案 2 - 如果您只需要某个路由/组件上的脚本。
-
安装postscribe:npm install --save postscribe
-
创建带有内容的plugins/postscribe.client.js文件:
import postscribe from 'postscribe'
export default (context, inject) => {
inject('postscribe', (elementId, scriptCode) => {
postscribe(elementId, scriptCode)
})
}
- 在
nuxt.config.js里面添加刚刚创建的文件:
export default {
...
plugins: [
...
{ src: '~/plugins/postscribe.client.js' }
...
],
...
}
- 在您的组件中执行以下操作:
<template>
<div id="add-script-here" />
</template>
<script>
...
mounted () {
// eslint-disable-next-line no-useless-escape
this.$postscribe('#add-script-here', '<script src="SCRIPT_URL"><\/script>')
// If you need to do something onload, then instead of the line above do it like this:
// this.$postscribe('#add-script-here', '<script onload="DO_SOMETHING_ONLOAD_HEAR" src="SCRIPT_URL"><\/script>')
}
...
</script>
通常脚本应该添加到head或body,但似乎postscribe不能这样做,所以我们使用add-script-here。