在 Vue.js 单文件组件中使用 jQuery 插件

我正在尝试在我的 Vue.js 单曲中使用 this jQuery 插件文件组件.

I am trying to use this jQuery plugin in my Vue.js single file component.

根据链接的自动完成插件的要求,我在 index.html 中导入了引用,以便它们在我需要使用 autocomplete 功能的所有其他 vue 组件中可用代码>输入框 .

as required in the linked autocomplete plugin I imported references in index.html, for them to be available all other vue components where I need to use autocomplete feature in input field .

  <script src="//code.jquery.com/jquery-1.12.4.js"></script>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
        <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

但是当我在我的单个文件组件的脚本标记中包含以下代码时.

But when I include below code in the script tag of my single file component.

 $("#autocomplete").autocomplete({
        source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
    });

我得到错误控制台说:

> TypeError: $("#autocomplete").autocomplete is not a function. (In
> '$("#autocomplete").autocomplete({
>     source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"] })', '$("#autocomplete").autocomplete' is undefined)

但我在 index.html

推荐答案

检查 html 中 js 文件/脚本的顺序.Vue 脚本可能在加载 jQuery 之前执行.将 jQuery 相关的脚本标签移到 Vue 脚本标签上方.您还可以通过检查 window.$ 的存在来安全地检查 jQuery 在您的 Vue 脚本中是否可用:

Check the order of js files/script inside your html. It's possible that the Vue script is executed before jQuery is loaded. Move jQuery-related script tags above Vue script tags. You can also safely check if jQuery is available in your Vue script by checking for existence of window.$:

if (typeof window.$ === 'function') {
  $("#autocomplete").autocomplete({
        source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
    });
}

相关文章