Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 289
Eric Liang Avatar asked Oct 15 '25 12:10

Eric Liang


1 Answers

[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!

like image 140
Eric Liang Avatar answered Oct 18 '25 00:10

Eric Liang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!