Nuxt: Set layout in page.vue dynamically based on data

Viewed 5574

Can I set the layout in my page based on a data variable?

I have the following folder structure:

layouts/
--default.vue
--custom.vue
pages/
--page.vue

I tried this in Page.vue:

export default {
  data () {
    return { value: '' }
  },
  layout () { this.value === 'a' ? 'custom' : 'default' }
  async asyncData ({...}) { //value is set here }

But it returns the error "cannot read property 'value' of undefined". How can I access what's in data to dynamically decide which layout the page should use?

3 Answers

The docs says that layout can also be a function (with access to the context).

export default {
  layout: 'blog',
  // OR
  layout (context) {
    return 'blog'
  }
}

I guess that in the context is everything you need.

layout ({$auth}) { return $auth.loggedIn ? 'layout1' : 'layout2' }

You cannot change layout dynamically in page because layout is parent of this page and you cannot change it from it's child

So try it to fetch data in layout and change it in layout level !

Related