javascript - 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.
我一直在寻找解决方案一段时间,但找不到解决方案。有人看到我在这里做错了吗?
提前致谢
解决方案
我发现了问题。在<nuxt/>
组件内部也是一个引用isSmallScreen
。在页面重新加载时,数据中不存在该属性。那是因为我命名了我的 mixins 文件mixins.client.js
在文档中有一个关于Name 常规插件的部分,这意味着它file.client.js
只会在客户端上运行,并且file.server.js
只能在 SSR 上运行。这就是为什么我的 mixin 插件中的数据不可用导致警告的原因。
更改我的 mixins 文件名来mixins.js
为我解决问题。
推荐阅读
- java - 如何将自定义键事件发送到小程序?
- python - 使用 Python 插件从 Python virtulenv 运行 VIM
- azure - 无法在存储资源管理器中打开 Cosmos DB 文档
- php - 数组最后返回一个额外的“1”(Codeigniter)
- python - Matplotlib 代码,用于 3D 表面上的 3D 线动画
- xcode - 为什么我不能提交到 GitHub?
- c++builder - 如何在 RAD 工作室中使用 TLang 翻译 MainMenu?
- amazon-web-services - 如何让 Lambda 函数递归调用自身
- javascript - 单元测试异步快速中间件
- bash - 管道输出到 uniq 或 sort -u 不返回预期结果