首页 > 解决方案 > Nuxt mixin - 属性或方法未在实例上定义,但在渲染期间引用

问题描述

我正在创建一个 Nuxt 应用程序,其中一个特定的菜单应该隐藏在移动设备上。所以我创建了一个 mixin 插件,它的属性isSmallScreen可以是false或真。

mixins.client.js

import Vue from 'vue'
import styles from '@/assets/styles/base/globals/_responsive.scss'

const debug = true

let breakpoint = parseInt(styles.breakpoint, 10)

Vue.mixin({
  data: function() {
    return {
      isSmallScreen: null
    }
 },
 created() {
    this.isSmallScreen = (window.innerWidth <= breakpoint)
  }
})

我已经注册了 mixins 插件nuxt.config.js

plugins: [
  '~/plugins/base/global/mixins.client.js',
]

现在我希望isSmallScreen在全球范围内可用。当我 console.logthis.isSmallScreen进入挂载的钩子时layouts/default.vue,它会返回true小屏幕和false大屏幕。这似乎工作正常。

问题

我的 default.vue 布局模板看起来像

<template>
<div>

  <client-only>
    <div class="nav-container">
      <f-nav-admin />
      <f-nav-top v-if="!isSmallScreen"/>
    </div>
  </client-only>

  <!-- page content -->
  <div class="page-content-container">
    <nuxt />
  </div>

</div>
</template>

我希望该f-nav-top组件确实出现在大屏幕上,并隐藏在小屏幕上。这似乎也有效。

但 ..

即使该功能做了它应该做的事情,我仍然会收到如下所示的警告。

Property or method "isSmallScreen" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

我一直在寻找解决方案一段时间,但找不到解决方案。有人看到我在这里做错了吗?

提前致谢

标签: javascriptvue.jsnuxt.jsmixins

解决方案


我发现了问题。在<nuxt/>组件内部也是一个引用isSmallScreen。在页面重新加载时,数据中不存在该属性。那是因为我命名了我的 mixins 文件mixins.client.js

文档中有一个关于Name 常规插件的部分,这意味着它file.client.js只会在客户端上运行,并且file.server.js只能在 SSR 上运行。这就是为什么我的 mixin 插件中的数据不可用导致警告的原因。

更改我的 mixins 文件名来mixins.js为我解决问题。


推荐阅读