Enrique Bermúdez
Enrique Bermúdez

Reputation: 115

Uncaught ReferenceError: $ is not defined (VueJS)

I've started a VueJS project with:

vue init webpack my-project

And got jQuery with npm:

npm install jquery

And i put this line on my main.js file:

window.$ = window.jQuery = require('jquery')

Either way, i can't use this piece of code: (from semantic ui)

$('.ui.rating')
  .rating()
;

Because i get this error:

Uncaught ReferenceError: $ is not defined

Any idea why this is happening ?

Upvotes: 9

Views: 63343

Answers (3)

Samanja Cartagena
Samanja Cartagena

Reputation: 150

It wasn't working for me as well but I did this following trick. At first I installed jquery with

npm install jquery

I did not need to make jquery global or the $ global in my in my main.js. Instead I directly imported it in the components

  <template>
  <div>
  <ul class="nav">
  <li class="active">
  <a href="#">Home</a>
  </li>
  <li><a href="#">Link</a></li>
  <li><a href="#">Link</a></li>
  </ul>
  </div>
  </template>
  <script>
  import jquery from 'jquery'
  export default {
  name: 'App',
  components: {
  },
  data(){
  return {

  }
 },
 mounted(){
 this.$nextTick(()=>{
 jquery('.nav').hide()
       })
  }
 }
 </script>

So just use jquery instead of the $ sign.

Upvotes: 0

Abdelsalam Shahlol
Abdelsalam Shahlol

Reputation: 1769

It's better to keep your jQuery code separated from Vue code. You can achieve that by creating a jQuery file in assets and use ECMAScript export and import feature.

 //your jQuery functions file e.g main.js
    import $ from 'jQuery' //import jQuery 

    export function somethingWithjQuery(){
     console.log($)
     }

And inside of your Vue component you can do something like this:

 import {somethingWithjQuery} from './assets/js/main'

    export default {
        name: 'app',
        components: {
            Hello
        },
        mounted() {
            somethingWithjQuery()
        }
    }

Upvotes: 1

samayo
samayo

Reputation: 16495

If you have jQuery installed via npm, just import it like this:

import $ from 'jquery'

And inside your methods, you can start using $ as:

methods: {
  getFoo() {
    $( "div.foo" ).html();
  }
}

Upvotes: 21

Related Questions