jQuery 未捕获的 ReferenceError:$ 未定义(VueJS)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48523951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught ReferenceError: $ is not defined (VueJS)
提问by Enrique Bermúdez
I've started a VueJS project with:
我已经开始了一个 VueJS 项目:
vue init webpack my-project
And got jQuery with npm:
并使用 npm 获得 jQuery:
npm install jquery
And i put this line on my main.js file:
我把这一行放在我的 main.js 文件中:
window.$ = window.jQuery = require('jquery')
Either way, i can't use this piece of code: (from semantic ui)
无论哪种方式,我都不能使用这段代码:(来自语义ui)
$('.ui.rating')
.rating()
;
Because i get this error:
因为我收到此错误:
Uncaught ReferenceError: $ is not defined
Any idea why this is happening ?
知道为什么会这样吗?
回答by samayo
If you have jQuery installed via npm, just import it like this:
如果您通过 npm 安装了 jQuery,只需像这样导入它:
import $ from 'jquery'
And inside your methods, you can start using $
as:
在你的方法中,你可以开始使用$
:
methods: {
getFoo() {
$( "div.foo" ).html();
}
}
回答by Abdelsalam Shahlol
It's better to keep your jQuerycode separated from Vuecode. You can achieve that by creating a jQuery file in assets and use ECMAScriptexport
and import
feature.
最好将jQuery代码与Vue代码分开。您可以通过在资产中创建一个 jQuery 文件并使用ECMAScriptexport
和import
功能来实现这一点。
//your jQuery functions file e.g main.js
import $ from 'jQuery' //import jQuery
export function somethingWithjQuery(){
console.log($)
}
And inside of your Vuecomponent you can do something like this:
在Vue组件中,您可以执行以下操作:
import {somethingWithjQuery} from './assets/js/main'
export default {
name: 'app',
components: {
Hello
},
mounted() {
somethingWithjQuery()
}
}