Home  >  Article  >  Web Front-end  >  Tutorial on how to use jQuery in Vue

Tutorial on how to use jQuery in Vue

小云云
小云云Original
2017-12-13 14:06:341619browse
本文主要和大家分享Vue 中使用 jQuery的方法教程,编译报错:
$ is undefined or no-undef '$' is not defined
,
假设你已经使用vue-cli搭建好了开发的脚手架,接下来如下:


Install jQuery, run the following code in the project root directory

npm install jquery --save

webpack configuration

Find the webpack.base.conf.js file in the build directory under the project root directory. Use the following code at the beginning to introduce webpack, because the file is not referenced by default

var webpack = require('webpack')

Then add a piece of code in 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: [// ......
  ]
}

Then many other solutions say that importing it in main.js is enough, but the questioner did so. Import jQuery in main.js:

import 'jquery'

Use $ or jQuery in the Vue component to write the code to operate the dom. Then start the project:

npm run dev

But the compilation error is reported:

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

What's going on? ? ?

eslint check

Smart friends must have thought that it is related to eslint. Yes, the next step you need to do at this time is to modify the .eslintrc.js file in the root directory. After changing the file In module.exports, just add a key-value pair jquery: true to env, that is:

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

npm run dev again, OK, no error is reported, quickly go to the component and try it, console. log($('selector')) , you will find that the DOM is successfully obtained using jQuery.

Related recommendations:

Detailed explanation of the three writing forms of vue components

Detailed explanation of vue code method for adding vux

TypeScript improvements in Vue 2.5

The above is the detailed content of Tutorial on how to use jQuery in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn