如何将 jQuery 安装到 Nuxt.js 中? [英] How to install jQuery into Nuxt.js?

查看:30
本文介绍了如何将 jQuery 安装到 Nuxt.js 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的项目中添加 jQuery,尽管我收到未定义的错误

I'm trying to add jQuery in my project although i get an error that it is not defined

  plugins: [
    { src: '~/plugins/js/svgSprite.js', mode: 'client' },
    { src: '~/plugins/vendor/jquery/jquery.min.js', mode: 'client' },
    { src: '~/plugins/vendor/bootstrap/js/bootstrap.bundle.min.js', mode: 'client' },
    { src: '~/plugins/vendor/bootstrap-select/js/bootstrap-select.min.js', mode: 'client' }, <-- gives me error
    { src: '~/plugins/vendor/magnific-popup/jquery.magnific-popup.min.js', mode: 'client' },
    { src: '~/plugins/vendor/smooth-scroll/smooth-scroll.polyfills.min.js', mode: 'client' },
    { src: '~/plugins/vendor/object-fit-images/ofi.min.js', mode: 'client' },
    { src: '~/plugins/js/theme.js', mode: 'client' }
  ],

为什么会发生这种情况,我显然是在 bootstrap-select 之前声明了 jQuery.

Why is this happening, I'm obviously declaring jQuery before bootstrap-select.

推荐答案

我不建议将 jQuery 添加到 Nuxt 项目中.

I do not recommend adding jQuery to a Nuxt project.

但如果您真的愿意,您可以按照以下步骤操作:

But if you really want to, you can follow those steps:

  • yarn add jquery
  • 安装它
  • 将这些添加到您的 nuxt.config.js 文件
import webpack from 'webpack'

export default {
  // ...
  build: {
    plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
      })
    ]
  },
}

  • 确保您的 .eslintrc.js 文件中有以下内容
    • be sure that you do have the following in your .eslintrc.js file
    • module.exports = {
        // ...
        env: {
          // ...
          commonjs: true,
          jquery: true
        },
      }
      

      然后,您可以像这样在 method 或类似的地方使用它

      Then, you can use it like this in a method or alike

      $("h2").addClass("tasty-class")
      

      这篇关于如何将 jQuery 安装到 Nuxt.js 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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