首页 > 技术文章 > Vue Cli 中使用 jQuery

haohaogan 2022-04-28 16:56 原文

 方式一:

1、安装 jquery

npm install jquery

2、在想要使用 jQuery 的文件里面引入即可:

import $ from 'jquery

 

注意:如果要在 main.js 文件里面引入 jQuery ,则需要这样加:

import $ from 'jquery'
window.$ = $  //原因:设置变量但未使用,编辑器会报错。

不要这样添加:【import $ from 'jquery'       Vue.use($)】,否则出现报错:【Vue is a constructor and should be called with the `new` keyword】【this._init is not a function】 

 

方式二:

1、安装 jquery

npm install jquery

2、在 vue.config.js 文件里面添加(没有此文件则自行创建):

const webpack = require('webpack')
module.exports = {
    configureWebpack: {
        plugins: [
            new webpack.ProvidePlugin({ //配置插件全局使用 jquery
                $: 'jquery',
                jQuery: 'jquery',
                'windows.jQuery': 'jquery' 
            })
        ]
    }
}

3、 一定要重新 run dev

4、在想要使用 jQuery 的文件里面引入即可:(或者可以不用引入,直接使用即可)

import $ from 'jquery

 

注意:如果要在 main.js 文件里面引入 jQuery ,则需要这样加:

import $ from 'jquery'
window.$ = $  //原因:设置变量但未使用,编辑器会报错。

不要这样添加:【import $ from 'jquery'       Vue.use($)】,否则出现报错:【Vue is a constructor and should be called with the `new` keyword】【this._init is not a function】 

 

方式三:

1、安装 jquery

npm install jquery

2、在 webpack.base.conf.js 文件里面添加(没有此文件则自行创建):

const webpack = require('webpack')
module.exports = {
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
    ]
}

3、在想要使用 jQuery 的文件里面引入即可:

import $ from 'jquery

 

 

注意:如果要在 main.js 文件里面引入 jQuery ,则需要这样加:

import $ from 'jquery'
window.$ = $  //原因:设置变量但未使用,编辑器会报错。

不要这样添加:【import $ from 'jquery'       Vue.use($)】,否则出现报错:【Vue is a constructor and should be called with the `new` keyword】【this._init is not a function】 

 

方式四:

1、安装 jquery

npm install jquery

2、在 webpack.base.conf.js 文件里面添加(没有此文件则自行创建):

const webpack = require('webpack')
module.exports = {
    resolve: {
        extensions: ['', '.js', '.vue'],
        fallback: [path.join(__dirname, '../node_modules')],
        alias: {
            'src': path.resolve(__dirname, '../src'),
            'assets': path.resolve(__dirname, '../src/assets'),
            'components': path.resolve(__dirname, '../src/components'),
            'jquery': path.resolve(__dirname,  '../node_modules/jquery/src/jquery'),// ==============添加这一句==================
        }
    },
}

 

3、在想要使用 jQuery 的文件里面引入即可:

import $ from 'jquery

 

注意:如果要在 main.js 文件里面引入 jQuery ,则需要这样加:

import $ from 'jquery'
window.$ = $  //原因:设置变量但未使用,编辑器会报错。

不要这样添加:【import $ from 'jquery'       Vue.use($)】,否则出现报错:【Vue is a constructor and should be called with the `new` keyword】【this._init is not a function】 


如有问题,请提醒我,以便改正!

推荐阅读