Nuxt.js: How to dynamic switch theme

Created on 31 Oct 2017  路  8Comments  路  Source: nuxt/nuxt.js

I have a need, I want to create a company offical site, different company has different theme, and when visit one company page, I must specify the compnay id, and get the theme by the id from api (async), then render different UI component by different theme.

for example I visit http://xxxx?company=1 will render the red theme and I visit http://xxxx?company=2 will render the blue theme

so I struct the project like:

  -red
      index.vue
  -blue
      index.vue

but the result is nuxt always root the view page to pages can't specify a rule, so how can I realize this?

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

Most helpful comment

@bimohxh you need to use beforeCreate hook for using this, see https://github.com/nuxt/nuxt.js/blob/dev/examples/async-component-injection/pages/_slug.vue#L16

export default {
  asyncData ({query}) {
    let res = axios().get(`company/theme?id=xxx`)
    return {
      theme: res.data
    }
  },
  beforeCreate () {
    this.News = () => import(`~/components/templates/${this.theme}/news.vue`)
  },
  components: {
    Logo
  }
}

All 8 comments

@bimohxh I think layout property can be used to achieve it.
layout property can be set a function and it receives context property.
https://nuxtjs.org/api/pages-layout#the-layout-property

@dotneet thnaks, but I need different page vue, not layout

For your case, I suggest you to have only one pages/index.vue which render different component based on $route.query.company

@Atinux I have think this, but nuxt dynamic import component didn't support parameter, I write code like this

export default {
  asyncData ({query}) {
    let res = axios().get(`company/theme?id=xxx`)
    return {
      theme: res.data
    }
  },
  components: {
    Logo,
    News: () => import(`~/components/templates/${this.theme}/news.vue`)
  }
}

@bimohxh you need to use beforeCreate hook for using this, see https://github.com/nuxt/nuxt.js/blob/dev/examples/async-component-injection/pages/_slug.vue#L16

export default {
  asyncData ({query}) {
    let res = axios().get(`company/theme?id=xxx`)
    return {
      theme: res.data
    }
  },
  beforeCreate () {
    this.News = () => import(`~/components/templates/${this.theme}/news.vue`)
  },
  components: {
    Logo
  }
}

@Atinux You are a great man, nuxt is a great framework

Thank you :)

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

danieloprado picture danieloprado  路  3Comments

gary149 picture gary149  路  3Comments

maicong picture maicong  路  3Comments

nassimbenkirane picture nassimbenkirane  路  3Comments

vadimsg picture vadimsg  路  3Comments