如何将客户端脚本添加到Nuxt.js?

3

我一直在阅读Nuxt.js关于插件和配置nuxt文件添加脚本的文档。我尝试了两种方法,但没有成功。

我想要添加以下代码(位于/static/js/scripts.js):

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

请问有人可以帮助我吗?

在常规的HTML用法中,我只需将脚本标签放在闭合的body标签之前(为了用户体验)。我成功地使scripts.js在Vue.js 2.0框架中加载,但是一旦我把所有东西都移到Nuxt.js,并尝试适应Nuxt.js,除了scripts.js文件外,其他所有东西都正常工作。

2个回答

6

[已解决]!

我找到了解决方法!由于Nuxt.js文档没有帮助我,所以我不得不回到Vue.js文档。

因此,我基本上进入了包含导航栏的vue文件,我想要在滚动时切换类出现。我还必须修改javascript代码,使其符合ESLINT标准... 因此,在下面的代码中,相当于我在问题中写的内容。

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

一旦这个问题解决了,我需要在同一个文件的模板标签中使用vue绑定类。

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

之后一切都完美地运行了!


1

Nuxt v1.4.0官方指南在这里: 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']
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接