Nuxt.js: How to handle conditional rendering that involves window?

Created on 9 Mar 2017  路  4Comments  路  Source: nuxt/nuxt.js

Hi, I used nuxt to render a vue template that involves v-if.

// template
<header v-if="checkMobile()"></header>

// script
export default {
  methods: {
    checkMobile() {
      return window ? window.innerWidth < 768 : true
    }
}

This may cause different rendering result between server and client due to window.innerWidth.
And this raises an error:

The client-side rendered virtual DOM tree is not matching server-rendered content.

So, how should I handle conditional rendering that involves window?

Thank you!

This question is available on Nuxt.js community (#c312)

Most helpful comment

I came across a solution:

<component :is="compo"></component>

// script
import Header from '~components/header.vue'

export default {
  data() {
    return {
      compo: null
    }
  }, 

  mounted() {
    this.compo = this.checkMobile() ? Header : null
  },

  methods: {
    checkMobile() {
      return window ? window.innerWidth < 768 : true
    }
}

The idea behind it is that, the server will not render tag at all, and it's up to the client to execute code in mounted() to determine what to render in it.

All 4 comments

if (process.BROWSER_BUILD) { ... }

@oguzhanaslan Thanks for replying!

But the problem I got is not about determining whether it's in node.js or browser environment,
it's about the inconsistence between server rendered content and the client rendered content,
which raises the error I posted.

I came across a solution:

<component :is="compo"></component>

// script
import Header from '~components/header.vue'

export default {
  data() {
    return {
      compo: null
    }
  }, 

  mounted() {
    this.compo = this.checkMobile() ? Header : null
  },

  methods: {
    checkMobile() {
      return window ? window.innerWidth < 768 : true
    }
}

The idea behind it is that, the server will not render tag at all, and it's up to the client to execute code in mounted() to determine what to render in it.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mikekidder picture mikekidder  路  3Comments

uptownhr picture uptownhr  路  3Comments

maicong picture maicong  路  3Comments

surmon-china picture surmon-china  路  3Comments

bimohxh picture bimohxh  路  3Comments