Nuxt mixin - Property or method is not defined on the instance but referenced during render

Viewed 2068

I'm creating a Nuxt application, where a specific menu should be hidden on mobile. So i've created a mixin plugin that has the property isSmallScreen which can be false or true.

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)
  }
})

I've registered the mixins plugin in nuxt.config.js

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

Now I expect isSmallScreen to be globally available. When I console.log this.isSmallScreen in the mounted hook in layouts/default.vue, it returns true for small screens, and false for bigger screens. That seems to work fine.

The problem

My default.vue layout template looks like

<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>

I expect the f-nav-top component do appear on large screens, and hide on small screens. Which also seems to work.

But ..

Even though the functionality does what it should I still get the warning as shown below.

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.

I've been looking for a solution for a while now, but can't find the solution. Does anyone see what I'm doing wrong here?

Thanks in advance

1 Answers

I've found the problem. Inside the <nuxt/> component was a reference to isSmallScreen as well. On page reload, the property didn't exists on the data though. That's because I named my mixins file mixins.client.js

In the documentation there is a part about Name conventional plugin which means that file.client.js will only run on the client, and file.server.js only SSR. So that's why the data from my mixin plugin was not available which resulted in the warning.

Changing my mixins filename to mixins.js did the fix for me.

Related