在使用ssr后,vue中window变量报错
来源:5-3 服务端渲染的entry配置
夏筱晗
2019-12-19
在使用serverRenderer打包客户端、服务端后,我先启动了客户端,然后时服务端,打包过程也正常,只不过在渲染服务端页面时,服务端控制台报了一个错:
renderer error ReferenceError: window is not defined
at Object.module.exports.r (src/store/index.js:229:12)
at __webpack_require__ (webpack:/webpack/bootstrap 0af5a49ba2806dc9808d:25:0)
at Object.<anonymous> (src/create-app.js:1:0)
at __webpack_require__ (webpack:/webpack/bootstrap 0af5a49ba2806dc9808d:25:0)
at Object.<anonymous> (entry.server.js:21934:70)
at __webpack_require__ (webpack:/webpack/bootstrap 0af5a49ba2806dc9808d:25:0)
at module.exports.__webpack_exports__.d (webpack:/webpack/bootstrap 0af5a49ba2806dc9808d:90:0)
at Object.<anonymous> (entry.server.js:95:10)
at evaluateModule (C:\Users\xiayi\Desktop\szh-vue-ssr\node_modules\vue-server-renderer\build.dev.js:9303:21)
at C:\Users\xiayi\Desktop\szh-vue-ssr\node_modules\vue-server-renderer\build.dev.js:9339:17
Error: ReferenceError: window is not defined
at module.exports (C:\Users\xiayi\Desktop\szh-vue-ssr\server\router\server-render.js:16:11)
at process._tickCallback (internal/process/next_tick.js:68:7)
说的是项目中使用的window变量未定义,这里涉及一个需求,就是我的Vue项目需要适应屏幕大小,我需要获取window.innerHeight与window.innerWidth,这个情况怎么办?
下面是我处理屏幕自适应的部分的代码:
<template>
<div :style="fullComputedStyle">
....
</div>
</template>
<script>
import personalCenter from './components/personalCenter'
import {mapState} from 'vuex'
export default {
name: 'App',
data() {
return {
screenWidth: window.innerWidth,
screenHeight: window.innerHeight
}
},
components: {
personalCenter
},
computed: {
fullComputedStyle() {
return "width: " + this.screenWidth + "px; height: " + this.screenHeight + "px; min-height: 717px;"
},
...mapState(['userId', 'current'])
},
created: function () {
this.init();
},
methods: {
init() {
this.menuLevel = "1";
let that = this;
window.onresize = () => {
that.screenWidth = window.innerWidth;
that.screenHeight = window.innerHeight;
}
},
refreshCurrent() {
console.log(1);
this.$store.commit("setShowViewer", false);
this.$nextTick(() => {
this.$store.commit("setShowViewer", true);
})
}
}
}
</script>
同时,项目里其他页面也有使用window的地方,怎么才能在全局使用window呢?
写回答
1回答
-
Jokcy
2019-12-19
因为服务端渲染没有window变量,window是浏览器特有的js公共变量。所以在服务端渲染的过程中需要屏蔽dom操作
032019-12-30
相似问题