由於項目需求要使用jquery,結果各種引用都不濟於事。
最后在網上找到了答案,現把它記錄一下,給有需要者。
首先下載 jquery。
cnpm install jquery --save-dev
方案一:
然后在main.js中引入jquery。
import Vue from 'vue' import $ from 'jquery' //加上這句話 import App from './App.vue' Vue.config.productionTip = false Vue.prototype.$ = $; // 當然還有這句話 給vue原型上添加 $ new Vue({ render: h => h(App), }).$mount('#app')
在使用的時候
mounted() { console.log(this.$('#wrapper')); }
這樣使用的時候會有一些麻煩,比如在一個函數內部使用的時候,this的指向是個問題。
方案二:
這個就比較簡單粗暴了,直接在需要使用jquery的組建中
<script> import $ from 'jquery' export default { // $("nav").click() ... }
==============================
如果以上還解決不了試試如下:
方式一 全局使用
1)main.js中引入
1
2
3
|
// jquery
import $
from
'jquery'
Vue.prototype.$ = $;
|
2)更改vue.config.js
1
2
3
4
5
6
7
8
9
10
11
|
const
webpack = require(
'webpack'
)
configureWebpack: {
plugins: [
new
webpack.ProvidePlugin({
$:
'jquery'
,
jQuery:
'jquery'
,
'windows.jQuery'
:
'jquery'
})
]
}
|
3)重要!!!.eslintrc.js中添加節點,否則編譯會報錯
1
|
jquery:
true
|
方式二 組件中使用(直接引用即可)
1
|
import $
from
'jquery'
|
此外:jquery要使用的話最早要在 mounted中
參考文章: https://blog.csdn.net/qq_35430000/article/details/80960423
https://www.cnblogs.com/JahanGu/p/12667784.html