5
votes

I am using vue.js version 2.5.13 installed with the vue-cli using the webpack-template.

Now I would like to use the generated App.vue-template for all my public pages and another template AdminApp.vue for all my admin-routes.

My router/index.js is like this:

import Vue from 'vue'
import Router from 'vue-router'
import LandingPage from '@/components/LandingPage'
import AdminDashboard from '@/components/admin/AdminDashboard'

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      name: 'LandingPage',
      component: LandingPage
    },{
      path: '/admin/dashboard ',
      name: 'AdminDashboard',
      component: AdminDashboard
    }
}

My main.js is like this:

import Vue from 'vue';
import App from './App.vue';
import AdminApp from './AdminApp.vue';
import router from './router';

if (window.location.href.includes('/admin/')) {
  new Vue({
    el: '#app',
    router,
    components: {AdminApp},
    template: '<AdminApp/>'
  });
} else {
  new Vue({
    el: '#app',
    router,
    components: {App},
    template: '<App/>'
  });
}

Now if I go to localhost:8080/#/ and then via url to localhost:8080/#/admin/dashboard the admin-panel does not use the AdminApp.vue-Template but the App.vue-Template. If I refresh this page, it works.

Do you know why? Are there some best practices for using two or more different templates for different routes?

Kind regards, Rokko

1
Can you demonstrate same on a fiddle? or share your repo?Dani Vijay
Is main.js being executed every time the route changes, or only when a real page load happens?Roy J
You're doing it wrong, no need to have 2 vue instances depending on the path, Vue router takes care of that for you. Let me try to create an example for you following your code.Stark
Here, this will give you an idea how you should do things jsfiddle.net/o4dup5gu/10Stark
Thank you @Craig, I had the same problem and this helps me in 2020.chrizonline

1 Answers

0
votes

In Brief:

You should make your layouts.For example layout1 & layout2. Then you should define them as global component in your main.js and finally use them with v-if in your app.vue depends on your condition.

With Detail:

first in router/index.js:

    {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/auth/login',
    name: 'login',
    meta:{layout:"auth"},
    component: Login
  },

which first route will render with admin layout and second one render with Auth layout for example. Now in main.js we will define layouts as component:

import Admin from './Layouts/Admin.vue'
import Auth from './Layouts/Auth.vue'
Vue.component('Admin',Admin);
Vue.component('Auth',Auth);

Then in App.vue we check meta datas that passed from routes to detect which layout needs:

   <Auth v-if="this.$route.meta.layout==='auth'"/>
   <Admin v-if="this.$route.meta.layout==null"/>

Ok.All thins done!

Now we have two layout.