简体   繁体   English

尝试将外部脚本附加到Vue中的单个文件组件时出错

[英]Error trying to attach external script to single file component in Vue

I'm having a hard time linking an external script to a single file component in Vue. 我很难将外部脚本链接到Vue中的单个文件组件。 My application is structured like this: 我的应用程序的结构如下:

在此处输入图片说明

So the file I want to link to is components/Sshy and the destination file (I believe) would be ../javascripts/ 所以我想链接的文件是components / Sshy,目标文件(我相信)将是../javascripts/

This isn't my first time doing that, and I have other scripts connected that I have successfully referenced in other single file components as either: 这不是我第一次这样做,并且连接了其他脚本,这些脚本已在其他单个文件组件中成功引用为:

../javascripts/<name>
@/javascripts/<name> (Src is aliased) 

Like so: 像这样:

在此处输入图片说明

I'm trying to do the equivalent on a compiled file that isn't well suited to being exported as a module and imported like that. 我正在尝试对不太适合作为模块导出并像这样导入的已编译文件进行等效操作。 The suggestion I found on a way I could attach this script to a single file component is here . 我在路上我会这样脚本附加到一个单一的文件组件中发现的建议是在这里

I tried to copy this method like this: 我试图复制这种方法是这样的:

  mounted () {
     let testScript = document.createElement('script');
     testScript.async = true;
     testScript.type = "text/javascript";
     testScript.setAttribute('src','../javascripts/test.js');
     document.head.appendChild(testScript);
 },

But keep getting an error that seems to indicate it isn't picking up the file right. 但是不断出现错误,似乎表明它没有正确提取文件。 The error found is 发现的错误是

uncaught syntax error: Unexpected token < 

And devtools reports it like it is occurring in the index.html where my vue files get injected. devtools会报告它发生在index.html中,这是我的vue文件被注入的地方。 In searches, it looked like the real cause may be the file not being connected properly ( Here ) 在搜索中,真正的原因似乎是文件未正确连接( 在此处

I haven't managed to identify what the issue is still though. 我还没有找到问题所在。

An invalid src path (ie, ../javascripts/test.js ) is likely the problem. 无效的src路径(即../javascripts/test.js )可能是问题所在。 Your server is probably configured with an index.html fallback, which is returned for files not found. 您的服务器可能配置有index.html后备,如果找不到文件,则返回该后备。 You can confirm this in your browser's developer tools (find test.js in Network Panel). 您可以在浏览器的开发人员工具(在“网络面板”中找到test.js中确认这一点。 Since the HTML file (which probably begins with <head> ) is sourced into the <script> , you get a JavaScript syntax error for the < character of <head> . 由于HTML文件(可能以<head>开头)源于<script> ,因此对于<head><字符,您会遇到JavaScript语法错误。

You'll need to update the src path to be relative to the root document and not to the directory of the component. 您需要将src路径更新为相对于根文档而不是相对于组件目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM