【问题标题】:Vue/Webpack/Typescript - How to use jQuery PluginVue/Webpack/Typescript - 如何使用 jQuery 插件
【发布时间】:2019-02-16 18:42:11
【问题描述】:

我想将在我的 vue.js/Webpack 中选择的 jQuery 插件与 TypeScript 应用程序一起使用。

我读到最好将插件包装在自定义 Vue 组件中。

我安装了 NPM 包:

npm install jquery --save
npm install @types/jquery --save
npm install chosen-js --save
npm install @types/chosen-js --save

我的组件:

<template>
    <select>
        <option value="1">Test1</option>
        <option value="2">Test2</option>
    </select>
</template>

<script lang="ts">
    import { Component, Prop, Vue } from "vue-property-decorator";
    import $ from 'jquery';    
    import 'chosen-js';

    @Component
    export default class ChosenSelect extends Vue{
        @Prop()options!:string;
        @Prop()value!:string;

        mounted() {
            let vm = this;
            let el = $(vm.$el);
            console.log(el);
        }
    }
</script>

没有 import 'chosen-js' jQuery 正在工作 - 当我在另一个组件中使用该组件时,我会得到一个控制台输出。

使用 import 'chosen-js' 我只能从所选库中获得 Uncaught ReferenceError: jQuery is not defined

导入 jQuery 和 selected-js 并在 vue Typescript 组件中使用它的正确方法是什么。

【问题讨论】:

  • 为什么要在 Vue.js 旁边使用 jQuery?像 Vue.js 这样的框架的全部意义在于避免直接的 DOM 操作......
  • 因为存在一些非常优秀且功能强大的 jQuery 插件,但没有相同质量的 vue.js 实现。为什么“扔掉”所有工作多年的东西? ;-)
  • 因为您有滑块、图像库和菜单/导航系统等组件是用 jQuery 编写的。

标签: javascript jquery typescript vue.js webpack


【解决方案1】:

感谢https://medium.com/@NetanelBasal/typescript-integrate-jquery-plugin-in-your-project-e28c6887d8dc,我想通了

首先,安装jquery

npm install jquery --save
npm install @types/jquery --save

然后在你的任何组件中添加这个。

import * as $ from 'jquery';

通过执行类似的操作检查 jquery 是否工作

import * as $ from 'jquery';

export default class Home extends Vue {
  created () {
    this.test()
  }

  test () {
    console.log($('body'))  // It's work
  }
}

有时您需要等待加载 dom 才能执行您的 jquery 操作。

<template>
  <div class="home">
    <div id="test">wijfwoe</div>
  </div>
</template>

<script>
import * as $ from 'jquery';
export default class Home extends Vue {
  created () {
  }

  mounted () {
        let a = $('#test')[0];
        console.log(a.textContent);
  }
</script>

【讨论】:

    【解决方案2】:

    我建议使用特定于 Vue 的选择插件,而不必依赖基于 jQuery 的插件,这在某种程度上违背了使用 Vue 之类的 DOM 操作的目的。其中大多数已经引入了自己的组件,因此无需创建包装器。

    这里维护了一个很棒的 Vue 资源列表,不仅仅是插件:awesome-vue

    【讨论】:

    • 有一个 vue 插件 (vue-select) 试图重新创建 selected-js/select2 的功能,但它不如提到的 jQuery 库好,我不想浪费时间修改它如果有可能只插入 jQuery 插件......现在 - 即使它直接操作 DOM。
    猜你喜欢
    • 2017-10-02
    • 2018-04-01
    • 2020-10-17
    • 1970-01-01
    • 2021-02-25
    • 2023-03-10
    • 2020-11-19
    • 2018-12-16
    • 1970-01-01
    相关资源
    最近更新 更多