前言
从这一期开始,我会逐渐将一些在开发博客系统是碰到的问题做一些总结,首先是Nuxt.js;
考虑到博客虽然主要做为自己的笔记总结留存用,但也希望能够让更多人能够看到,还是决定上SEO优化;由于详情页是动态的,无法使用
prerender-spa-plugin进行预渲染,所以最后还是选了Nuxt.js
window或document is not defined
碰到这种报错,是由于nuxt.js会在服务端渲染页面,而服务端并没有window或document
- 官方给出的解决方案如下:
- 我的解决方案:
- 写一个返回顶部的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>
- 写一个插件放入
plugins文件夹中
/**
* 将goTop组件挂载到全局
*/
import Vue from 'vue'
import GoTop from '~/components/GoTop'
Vue.component('GoTop', GoTop)
- 将插件写入配置文件
nuxt.config.js
// 将插件写进引入 nuxt.config.js,并将ssr选项设置为false,这样服务端渲染时就不会渲染这个组件了
plugins: [
{
src: '~plugins/go-top',
ssr: false
}
]
- 总结
至此, 一个简单的返回顶部组件已经完成,一般碰到服务端无法渲染的组件都可以这样处理;
后续会添加
requestanimationframe版本的返回顶部来提升效果,setInterval版本就作为兼容低版本浏览器使用