Eric Liang
Eric Liang

Reputation: 124

How to Add Client-side Scripts to Nuxt.js?

I've been reading Nuxt.js's documentation on Plugins and the config nuxt file for adding scripts. I tried both, but no luck.

I'm trying to add the following code (located in /static/js/scripts.js):

 $(window).scroll(function(){
     if ($(window).scrollTop() >= 200) {
        $('nav').addClass('fixed-header');
     }
     else {
        $('nav').removeClass('fixed-header');
     }
 });

Can someone help me please?

In regular HTML usage, I just do the script tags before the closing body tag (for the sake of user experience). I was able to get the scripts.js to load in a Vue.js 2.0 framework, but once I moved everything to Nuxt.js, and tried to adapt it to Nuxt.js, everything else worked, except the scripts.js file.

Upvotes: 4

Views: 15978

Answers (2)

Tim Yao
Tim Yao

Reputation: 1147

The official guide in Nuxt v1.4.0 document is here: https://nuxtjs.org/faq/window-document-undefined#window-or-document-undefined-

If you need to specify that you want to import a resource only on the client-side, you need to use the process.browser variable.

For example, in your .vue file:

if (process.browser) {
  require('external_library')
}

If you are using this library within multiple files, we recommend that you add it into your vendor bundle via nuxt.config.js:

build: {
  vendor: ['external_library']
}

Upvotes: 1

Eric Liang
Eric Liang

Reputation: 124

[SOLVED]!

I figured it out! I had to refer back to the Vue.js documentation since the Nuxt.js documentation didn't help me at all.

So I basically went into the vue file that contained the navigation bar I wanted the class to toggle appear in based on scroll. I also had to modify the javascript so it's ESLINT friendly... So for the code underneath is the equivalent of what I wrote in my question.

<script>
export default {
  name: 'MainNav',
  data: function () {
    return {
      fixedOnScroll: false
    }
  },
  methods: {
    handleScroll () {
      if (window.scrollY >= 200) {
        this.fixedOnScroll = true
      } else {
        this.fixedOnScroll = false
      }
    }
  },
  created () {
    if (process.browser) {
      window.addEventListener('scroll', this.handleScroll)
    }
  },
  beforeUpdate () {
    if (process.browser) {
      window.addEventListener('scroll', this.handleScroll)
    }
  }
}
</script>

Once that was settled, I had to use the vue bind class in the template tag on the same file.

<nav class = "navbar-expand-lg text-center" v-bind:class="{ 'fixed-header': fixedOnScroll }">

Everything worked perfectly after that!

Upvotes: 6

Related Questions