Including Javascript snippet that starts with $ in Nuxt page – returns this.$ is not a function

Tags: ,



I’m often having difficulty figuring out how to include Javascript snippets in individual components/pages with Nuxt. In the code below, I am getting $ is undefined:

<script>
export default {
    created() {
        this.$('a[href*=#]:not([href=#])').click(function() {
            if (location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'') 
                || location.hostname == this.hostname) {

                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
                if (target.length) {
                    $('html,body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                    return false;
                }
            }
        });
    }
}
</script>

I’ve also tried removed this. – that gives me $ is undefined. Any help is appreciated – thanks

Answer

You’re trying to use a jQuery syntax request with the $ shortcut function, but jQuery is not included in Nuxt or Vue.

You can install it with npm:

$ npm install jquery

And use it in your component (without this):

<script>
import $ from 'jquery';


export default {
    created() {
        $(...).click(...);
    }
}


Another way is to import jQuery as global (see nuxt docs) in your nuxt.config.js:

export default {
  head: {
    script: [
      {
        src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'
      }
    ]
  }


Source: stackoverflow