在Vue项目中包含或初始化jQuery库的最佳方法是什么? [英] What is the best way to include or initialize jQuery library in Vue project?

查看:255
本文介绍了在Vue项目中包含或初始化jQuery库的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Vue项目中包含jQuery库的最佳方法是什么?

What is the best way to include the jQuery library in Vue project?

我正在使用vue-cli,webpack和路由器。我有单独的组件,我需要包含一些jQuery插件。如果我在索引文件中包含jQuery脚本,那么我就有从组件操作(触发)DOM的问题。所以我想在main.js或组件中包含所有脚本会更好吗?

I'm using a vue-cli, webpack and router. I have separate components and I need to include few jQuery plugins. If I include jQuery script in index file, then I have problem to manipulate (trigger) DOM from components. So I guess it's better to include all scripts in my main.js or components?

我需要实现 Venobox 插件。
这是基本的jQuery初始化

I need to implement Venobox plugin. This is basic jQuery initialization

$(document).ready(function(){
    $('.venobox').venobox(); 
});

在Vue我试过

  mounted () {
    $('.venobox').venobox();
  }

现在我遇到了jQuery的问题。 '$'未定义等。
在Vue项目中包含外部JS文件的最佳做法是什么?
有没有简单的方法来初始化jQuery插件?

Now I have problem with jQuery. '$' is not defined etc. What is the best practice to include external JS files in Vue project? Is there are ease way to initialize jQuery plugins?

谢谢!

推荐答案

如果它只是这个使用jQuery的组件,我会在它内部独占导入它,不会打扰任何其他东西。您的代码是正确的(在已挂载的生命周期挂钩中初始化 venobox ),但您还必须在组件内导入jQuery :

If it's only this one component that uses jQuery, I'd import it exclusively inside of it and wouldn't bother with anything else. Your code was correct (initialising venobox inside the mounted lifecycle hook), but you also have to import jQuery inside your component:

import $ from 'jquery';

export default {
  mounted () {
    $('.venobox').venobox();
  }
}

但是,如果你在其他组件中也使用jQuery ,我建议在这里查看这个答案 https://stackoverflow.com/a/39653758/2803743 。在此处粘贴选项1,以防它被删除/更改(使用Webpack的ProvidePlugin):

However, if you use jQuery inside other components as well, I suggest looking at this answer here https://stackoverflow.com/a/39653758/2803743. Pasting option 1 here in case it gets removed/changed (the use of Webpack's ProvidePlugin):


选项#1:使用ProvidePlugin

Option #1: Use ProvidePlugin

将ProvidePlugin添加到build / webpack.dev.conf.js和build / webpack.prod.conf.js中的plugins数组中,以便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'
  })
]

这篇关于在Vue项目中包含或初始化jQuery库的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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