Nuxt.js开发中碰到的问题(一)window 或 document is not defined

博客原文链接

前言

从这一期开始,我会逐渐将一些在开发博客系统是碰到的问题做一些总结,首先是Nuxt.js;

考虑到博客虽然主要做为自己的笔记总结留存用,但也希望能够让更多人能够看到,还是决定上SEO优化;由于详情页是动态的,无法使用 prerender-spa-plugin 进行预渲染,所以最后还是选了 Nuxt.js


window或document is not defined

碰到这种报错,是由于nuxt.js会在服务端渲染页面,而服务端并没有window或document

  • 官方给出的解决方案如下:

官方解决方案链接

  • 我的解决方案:
  1. 写一个返回顶部的vue组件

<!-- 利用setInterval实现一个返回顶部组件,速度step与组件出现滚动距离scroll可传值 -->

<template>
  <div id="go-top" v-if="isShow" @click="goTop" class="iconfont icon-arrowsupline"></div>
</template>

<script>
  export default {
    props: ['step', 'scroll'],
    data () {
      return {
        isShow: false
      }
    },
    created () {
      const $this = this

      window.onscroll = function () {
        if (document.documentElement.scrollTop + document.body.scrollTop > $this.scroll) {
          $this.isShow = true
        } else {
          $this.isShow = false
        }
      }
    },
    methods: {
      goTop () {
        const $this = this
        let timer = setInterval(function () {
          if (document.body.scrollTop) {
            document.body.scrollTop -= $this.step
            if (document.body.scrollTop <= 0) {
              document.body.scrollTop = 0
              clearInterval(timer)
            }
          } else {
            document.documentElement.scrollTop -= $this.step
            if (document.documentElement.scrollTop <= 0) {
              document.documentElement.scrollTop = 0
              clearInterval(timer)
            }
          }
        }, 23)
      }
    }
  }
</script>

<style lang="less" scoped>
#go-top {
  position: fixed;
  bottom: 100px;
  right: 50px;
  cursor: pointer;
  height: 50px;
  width: 50px;
  line-height: 50px;
  text-align: center;
  border: 2px solid #333;
  color: #333;
  font-size: 20px;
  border-radius: 5px;
  transition: all .5s;
  &:hover {
    border-radius: 50%;
    color: #fff;
    background: #333;
  }
}
</style>

复制代码
  1. 写一个插件放入 plugins 文件夹中


/**
* 将goTop组件挂载到全局
*/

import Vue from 'vue'
import GoTop from '~/components/GoTop'

Vue.component('GoTop', GoTop)

复制代码
  1. 将插件写入配置文件 nuxt.config.js


// 将插件写进引入 nuxt.config.js,并将ssr选项设置为false,这样服务端渲染时就不会渲染这个组件了

plugins: [
  {
    src: '~plugins/go-top',
    ssr: false
  }
]

复制代码
  1. 总结

至此, 一个简单的返回顶部组件已经完成,一般碰到服务端无法渲染的组件都可以这样处理;

后续会添加 requestanimationframe 版本的返回顶部来提升效果, setInterval 版本就作为兼容低版本浏览器使用

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值