Home > database >  Vuejs How To Use Multiple Template
Vuejs How To Use Multiple Template

Time:07-26

I want to use different components for admin panel-website. I try that;

// App.vue
<template>
    <PanelTemplate v-if="$route.meta.template == 'panel'"/>
    <WebsiteTemplate v-if="$route.meta.template == 'website'"/>
</template>

<script>
import PanelTemplate from './templates/PanelTemplate.vue'
import WebsiteTemplate from './templates/WebsiteTemplate.vue'
export default {
    components : {
        PanelTemplate,
        WebsiteTemplate
    }
}
</script>

// Router.js
  {
    path: "/panel/dashboard",
    name : "panel-index",
    component: PanelView,
    meta : { template : 'panel' }
  },
  {
    path : "/",
    name : "website-index",
    component : WebsiteView,
    meta : { template : 'website' }
  },

// PanelTemplate.vue - WebsiteTemplate.vue
<template>
    <router-view></router-view>
</template>

But that's not working. I try component tag too but that's not working too. I am seeing just white screen, both of components not calling. What should I do?

CodePudding user response:

The router-view tag should be present in App.vue and wrapped by one of the template components:


<template>
    <component :is="currentTemplate">
        <router-view></router-view>
    </component>
</template>

<script>
import PanelTemplate from './templates/PanelTemplate.vue'
import WebsiteTemplate from './templates/WebsiteTemplate.vue'
export default {
    computed:{
     currentTemplate(){
        return this.$route.meta.template
     }
    },
    components : {
        PanelTemplate,
        WebsiteTemplate
    }
}
</script>

CodePudding user response:

If you want each component to have its own separate template (most common case), just place it as <template> tag in the .vue file. You don't need to specify it in the route and it doesn't need an identifier.

Example .vue file structure (called SFC - single file component):

<template>
  /// template here
</template>
<script>
...
</script>
<style>
...
</style>

If you want to use the same template for multiple components, you could place any number of templates anywhere in your page. Since they need to be available at all times, they could be direct children of <body>:

<body>
  <div id="app">
    ...
  </div>
  <template id="panel-tpl">
    ...panel template content goes here
  </template>
</body>

Now you can use this template in as many components as you want, by setting the template property to #panel-tpl:

<script>
import { defineComponent } from 'vue'
export default defineComponent({
  template: '#panel-tpl',
  // the rest of your component
})
</script>

Note: This time, the template needs an identifier. Note the identifier (id) has to be unique across all the page's HTML (no other HTML element should have the same id).


Alternate syntax for template:

<script type="text/x-template" id="panel-tpl">
  // template contents here
</script>
  • Related