美文网首页
vue引入jquery

vue引入jquery

作者: 微光2020 | 来源:发表于2021-09-17 14:59 被阅读0次

有时候vue不好处理的,使用jquery可以轻松完成,引入之后可以混合开发。

1,package.json中安装jquery

npm i jquery@2.2.3 --save

2,vue.config.js中添加插件

const webpack = require('webpack');
module.exports = {
    configureWebpack: {
        plugins: [
            // 配置jquery
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery",
                "windows.jQuery": "jquery"
            }),
        ]
    }
};
  • 没有vue.config.js就手动在根目录创建一个

3,main.js中引入jquery

import Vue from 'vue'
import App from './App.vue'

const $ = require('jquery');//只添加此处

new Vue({
  render: h => h(App),
}).$mount('#app');
  • 为了兼容vue3,使用require

4,使用jquery

<template>
    <div class="game">
      <button @click="test">一个按钮</button>
  </div>
</template>
<script>
export default {
    methods: {
        test(){
           console.log($('.game'));
        },
    }
}
</script>
  • 点击按钮一个按钮,通过$('.game')获取了对象

相关文章