如何将jQuery添加到VuePress文件中

时间:2018-10-16 13:31:48

标签: javascript jquery vue.js vuepress

我有一个要用VuePress记录的项目,并且我有一个需要jQuery才能运行的小代码。我知道您可以添加内联脚本标记并将代码放入其中,但是我似乎无法添加jQuery。这是文件夹结构以及我尝试过的方法:

docs
   .vuepress
   -- dist
   -- public
      -- css
      -- js
         -- jquery-3.3.1.min.js
         -- scripts.js
   -- config.js
   components.md

和components.md中,我在末尾添加了以下内容:

<script src="/js/jquery-3.3.1.min.js"></script> 

在脚本标记中添加jquery时出现错误:

 Module not found: Error: Can't resolve '../../../../../../js/jquery-3.3.1.min.js?vue&type=script&lang=js&' in C:/Users/../docs
 @ ./node_modules/vuepress/lib/app/.temp/routes.js
 @ ./node_modules/vuepress/lib/app/app.js
 @ ./node_modules/vuepress/lib/app/clientEntry.js
 @ multi ./node_modules/vuepress/lib/app/clientEntry.js

module.exports.head中的config.js中添加css可以,但是由于某种原因,添加javascript不起作用(jquery被添加了,但是有时它可以起作用,并且在大多数情况下不起作用)。这是我在config.js中尝试过的

head: [
["link",{ rel: "stylesheet", href: "/css/bootstrap-4.1.3/bootstrap reboot.css" } ],
["link",{ rel: "stylesheet", href: "/css/bootstrap-4.1.3/bootstrap-grid.css"}],
["link", { rel: "stylesheet", href: "/css/bootstrap-custom.css" }],
["link", { rel: "stylesheet", href: "/css/style.css" }],
["script", { src: "/js/jquery-3.3.1.min.js" }],
["script", { src: "/js/scripts.js" }]
]

编辑:我显然进行了更多测试,即使脚本已导入,也无法选择要选择的元素。例如$('。my-elements')返回一个空的选择器。另一方面,document.getElementsByClassName('my-elements')可以显示我想要的元素作为第一个数组元素,但是如果我想选择结尾为[0]的第一个数组元素,它将返回undefined。

我尝试使用上述2个功能在控制台中选择元素。相同的功能在控制台中起作用,但在脚本中不起作用,这很奇怪。

1 个答案:

答案 0 :(得分:0)

.vuepress/config.js

添加脚本

module.exports = {
    head: [
        ['script', {src: 'https://code.jquery.com/jquery-3.4.1.min.js'}]
    ]
}

有关头部配置的更多文档

  

https://vuepress.vuejs.org/config/#head

jQuery CDN

  

https://code.jquery.com/