【问题标题】:How to load static script files in Vue CLI 3如何在 Vue CLI 3 中加载静态脚本文件
【发布时间】:2019-08-22 06:58:26
【问题描述】:

我有一个使用 Vue CLI 2 制作的现有项目,我正在努力将其移至 Vue CLI 3,但我收到以下错误

1: "vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in created hook: "ReferenceError: _ is not defined"
2: "vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in mounted hook: "ReferenceError: $ is not defined"

我认为这是由于index.html。在 Vue CLI 2 中,index.html 位于项目根目录中,但 Vue CLI 3 将它放在 public 文件夹中。并且使用 Vue CLI 2 创建的项目会在 index.html 中加载 Jquery、Underscore、Bootstrap 等。

如何在 Vue CLI 3 中解决这些问题并获得与现有项目相同的结果?

Vue CLI 2 index.html

...
<!--Jquery -->
<script src="/blk/static/assets/lib/jquery/jquery.min.js"></script>
<script src="/blk/static/assets/lib/jquery/jquery-ui.min.js"></script>

<!--Bootstrap-->
<script src="/blk/static/assets/bootstrap/bootstrap.min.js"></script>
<script src="/blk/static/assets/bootstrap/moment-with-locales.min.js"></script>
<!-- <script type="text/javascript" src="scripts/moment-2.4.0.js"></script> -->
<script src="/blk/static/assets/bootstrap/bootstrap-datetimepicker.min.js"></script>

<script src="/blk/static/assets/lib/classie.js"></script>
<script src="/blk/static/assets/lib/custom.js"></script>
<!--underscore -->
<script src="/blk/static/assets/lib/underscore/underscore.js"></script>
...

导致问题的代码部分

const example = _.indexOf(path,'example'); // underscore not defined
...
$('#openDate').datetimepicker({ // "$" not defined
    locale: 'us',
    format: 'YYYY-MM-DD',
});

【问题讨论】:

  • 您可以尝试切换到这些库的 NPM 版本,然后将它们导入您的 main.js - 但我强烈建议您摆脱所有这些遗留问题。比如jQuery可以像window.$ = window.jQuery = require('jquery');这样导入
  • 您很可能是指 Vue CLI 2 和 Vue CLI 3,因为 Vue 3 尚不可用。
  • @IVO GELOV 我试过了,但我收到错误“[Vue warn]: Error in mounted hook:” TypeError: $ (...). Datetimepicker 不是函数”。
  • @tony19 是正确的。
  • 如果您尝试将这些 jQuery 插件(和 jQuery 本身)替换为与 Vue 兼容的替代品,您将遭受的痛苦会少得多。

标签: javascript vue.js


【解决方案1】:

让我们将 jQuery 与 Vue.js 集成

1。安装 jQuery

$ npm install jquery --save

2。检查你的 package.json

这是它的样子。它将添加具有特定版本的 jquery 库。

"dependencies": {
  "jquery": "^3.4.1"
}

3。在你的 vue 组件中定义 jQuery。

<template>
 <!-- HTML markup in here -->
</template>
<script>
window.$ = window.jQuery = window.jquery = require('jquery')

export default {
  name: 'component name'
}
</script>

【讨论】:

    猜你喜欢
    • 2018-12-11
    • 1970-01-01
    • 2018-09-09
    • 2020-07-17
    • 2019-08-20
    • 1970-01-01
    • 2020-07-13
    • 2019-03-08
    • 2021-04-07
    相关资源
    最近更新 更多