Vue 中使用 jQuery


題主Vue小白,入門demo時想在其中使用jQuery(當然可能是不推薦的做法哈,畢竟倆兒的風格不一樣,但萬一你就需要呢 _^ ^_),結果遇到問題,最終倒騰解決。

編譯報錯:$ is undefined or no-undef '$' is not defined

假設你已經使用vue-cli搭建好了開發的腳手架,接下來,看下面。。。

  1. NPM 安裝 jQuery,項目根目錄下運行以下代碼
npm install jquery --save
  1. webpack配置
    在項目根目錄下的build目錄下找到webpack.base.conf.js文件,在開頭使用以下代碼引入webpack,因為該文件默認沒有引用,
var webpack = require('webpack')

然后在module.exports中添加一段代碼,

// 原有代碼
resolve: {
  extensions: ['.js', '.vue', '.json'],
  alias: {
    'vue$': 'vue/dist/vue.esm.js',
    '@': resolve('src')
  }
},
// 添加代碼
plugins: [
  new webpack.ProvidePlugin({
    $: "jquery",
    jQuery: "jquery",
    jquery: "jquery",
    "window.jQuery": "jquery"
  })
],
// 原有代碼
module: {
  rules: [
    // ......
  ]
}

然后許多其他解決辦法到此就說在main.js里導入就可以了,然而題主照着做了。
main.js里導入jQuery

import 'jquery'

在Vue組件里使用 $ or jQuery 寫了操作dom的代碼
接着啟動項目

npm run dev

但是編譯卻報錯了:

http://eslint.org/docs/rules/no-undef '$' is not defined or
http://eslint.org/docs/rules/no-undef 'jQuery' is not defined

咋回事呢???
3. eslint 檢查
機智的朋友肯定想到跟eslint有關,沒錯,這時候需要做的下一步就是要修改根目錄下.eslintrc.js文件了,在改文件的module.exports中,為env添加一個鍵值對 jquery: true 就可以了,也就是:

env: {
  // 原有
  browser: true,
  // 添加
  jquery: true
}

再次 npm run dev ,OK了,沒報錯,趕緊去組件里試一下吧,console.log($('選擇器')) ,你會發現成功使用jQuery獲取到了DOM。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM