如何在Vue中使用jQuery插件 [英] How to use a jQuery plugin inside Vue

查看:1315
本文介绍了如何在Vue中使用jQuery插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在VueJS内构建Web应用程序,但是遇到问题.我想使用jQuery扩展(具体来说是cropit),但我不知道如何正确地实例化/要求/导入它而不会出错.

I'm building a web application inside VueJS but I encounter a problem. I want to use a jQuery extension (cropit to be specific) but I don't know how to instantiate/require/import it the right way without getting errors.

我正在为我的应用程序使用de官方CLI工具和webpack模板.

I'm using de official CLI tool and de webpack template for my App.

我在main.js文件中包含了这样的jQuery:

I included jQuery like this in my main.js file:

import jQuery from 'jQuery'
window.jQuery = jQuery

现在,我正在构建一个图像编辑器组件,我想在其中实例化蠕变,如下所示:

Now I'm building an image editor component where I want to instantiate crept like this:

export default {
  ready () {
    $(document).ready(function ($) {
      $('#image-cropper-wrapper-element').cropit({ /* options */ })
    })
  },
 }

但是我一直收到错误消息...现在我的问题是如何通过NPM/Webpack/Vue正确实例化jQuery和插件?

But I keep getting errors...Now my question is how to properly instantiate jQuery and plugins via NPM/Webpack/Vue?

提前谢谢!

推荐答案

选项1:使用ProvidePlugin

ProvidePlugin 添加到两个build/webpack.prod.conf.js,以便jQuery对您的所有模块全局可用:

Add the ProvidePlugin to the plugins array in both build/webpack.dev.conf.js and build/webpack.prod.conf.js so that jQuery becomes globally available to all your modules:

plugins: [

  // ...

  new webpack.ProvidePlugin({
    $: 'jquery',
    jquery: 'jquery',
    'window.jQuery': 'jquery',
    jQuery: 'jquery'
  })
]

选项2:对Webpack使用Expose Loader模块

正如@TremendusApps在他的回答中建议的那样,添加 Expose Loader 程序包:

As @TremendusApps suggests in his answer, add the Expose Loader package:

npm install expose-loader --save-dev

在入口点main.js中像这样使用:

Use in your entry point main.js like this:

import 'expose?$!expose?jQuery!jquery'

// ...

这篇关于如何在Vue中使用jQuery插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆