How to use same template on different components in vue js?

Currently I am using as

<template> ... </template>
<script src="test1.js"> </script>

Where all my business logics are written in test1.js. Now I need to use test2.js with same template. I need to reuse the template with different component.

My current code goes like this...

common.vue

<template>
 <div>
   {{ page }}
 </div>
<template>

<script src="../scripts/test1.js"></script>

Where in test1.js

export default {
  name: 'home',
  components: {
    test: test
  },
  data() {
    return {
        page: "test1",
    }
  }
}

But also i need to use common.vue in my test2.js. Which i am not able to import both the .js seperately.

In angular we can write the fallowing late bindig which binds .html and .js(in ui.router)

    .state('home', {
        url:'/',
        templateUrl: 'templates/home.html',
        controller: 'HomeController'
    })

Is there something similar to this?

Upvotes: 1

Views: 3615

Answers (1)

user6748331
user6748331

Reputation:

You can share the template through the id attribute.

Vue.component('my-comp1', {
  template: '#generic',
  data () {
    return {
      text: 'I am component 1'
    }
  }
})

Vue.component('my-comp2', {
  template: '#generic',
  data () {
    return {
      text: 'I am component 2'
    }
  }
})

new Vue({
  el: '#app'
})
<div id="app">
  <my-comp1></my-comp1>
  <my-comp2></my-comp2>
</div>

<template id="generic">
  <div>
    <p>{{ text }}</p>
  </div>
</template>

<script src="https://unpkg.com/vue"></script>

Upvotes: 3

Related Questions