Klausette
Klausette

Reputation: 412

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

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?

Upvotes: 7

Views: 12151

Answers (3)

Mạnh Hoan Dương
Mạnh Hoan Dương

Reputation: 51

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

Upvotes: 3

soroush
soroush

Reputation: 756

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 !

Upvotes: -5

thopaw
thopaw

Reputation: 4054

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.

Upvotes: 22

Related Questions