Nuxt.js 中的“窗口未定义”

HM.*_*ark 29 vue.js nuxt.js

从 Vue.js 移植到 Nuxt.js 时出现错误。

我正在尝试vue-sessionnode_modules. 它编译成功,但在浏览器中我看到错误:

未定义 ReferenceError 窗口

node_modules\vue-session\index.js

VueSession.install = function(Vue, options) {
    if (options && 'persist' in options && options.persist) STORAGE = window.localStorage;
    else STORAGE = window.sessionStorage;
    Vue.prototype.$session = {
        flash: {
          parent: function() {
            return Vue.prototype.$session;
          },
Run Code Online (Sandbox Code Playgroud)

所以,我遵循了这个文档

rewardadd.vue

import VueSession from 'vue-session';

Vue.use(VueSession);

if (process.client) {
  require('vue-session');
}
Run Code Online (Sandbox Code Playgroud)

nuxt.config.js

  build: {
    vendor: ['vue-session'],
Run Code Online (Sandbox Code Playgroud)

但我仍然无法解决这个问题。

inn*_*wkc 31

2021 年 8 月更新

Window is not defined 错误结果来自 nodejs 服务器端脚本,无法识别仅浏览器原生的 window 对象。

从 nuxt v2.4 开始,您不需要添加process.clientorprocess.browser对象。

通常,您的 nuxt 插件目录结构如下:

~/plugins/myplugin.js

import Vue from 'vue';
// your imported custom plugin or in this scenario the 'vue-session' plugin
import VueSession from 'vue-session';

Vue.use(VueSession);
Run Code Online (Sandbox Code Playgroud)

然后在您nuxt.config.js的项目中,您现在可以使用以下两种方法将插件添加到您的项目中:

方法一:

将值为'client'mode属性添加到您的插件中

plugins: [
  { src: '~/plugins/myplugin.js', mode: 'client' }
]
Run Code Online (Sandbox Code Playgroud)

方法2:(在我看来更简单)

使用扩展名.client.js重命名您的插件,然后将其添加到nuxt.config.js插件中的插件中。Nuxt的2.4.x将认识到插件扩展作为在服务器端要呈现.server.js或客户端.client.js根据所扩展使用。

注意:添加没有.client.js.server.js扩展名的文件将在客户端和服务器端呈现插件。在这里阅读更多。

plugins: [
  { src: '~/plugins/myplugin.client.js' }
]
Run Code Online (Sandbox Code Playgroud)


Roc*_*coB 17

服务器端渲染端没有窗口对象。但快速解决方法是检查process.browser.

  created(){
    if (process.browser){
      console.log(window.innerWidth, window.innerHeight);
    }
  }
Run Code Online (Sandbox Code Playgroud)

这有点草率,但它有效。这是一篇关于如何使用插件做得更好的好文章


Ald*_*und 8

它的所有内容都包含在 nuxt文档和常见问题解答中。首先你需要让它成为一个插件。其次你只需要让你的插件客户端

plugins: [
  { src: '~/plugins/vue-notifications', mode: 'client' }
]
Run Code Online (Sandbox Code Playgroud)

此外,在 nuxt 2.x 中不使用供应商,并且如果它在插件中带有 ssr false,则不需要您的 process.client


ube*_*kel 8

在 Nuxt 3 中你process.client可以像这样使用:

if (process.client) {
  alert(window);
}
Run Code Online (Sandbox Code Playgroud)