Skip to content
Advertisement

Cloning a single file Vue component (template and functionality)

I currently have a Vue component that I use in one part of my application. I want to use this same component in another part of my application; however, I would like to make some minor changes to the CSS (change background colors etc.).

The easy but repetitive method would be to simply copy and paste the component into a new .vue file and make the respective CSS changes; however, is there a better way of achieving this effect?

Ideally, I want to be able to create a new Vue component, which imports the entire template as well as methods, props etc. I’ve looked into using extends; however, it doesn’t import the Vue template – just the functionality.

Advertisement

Answer

You can pass a css class name as props :

Vue.component('my-component', {
  template: '#my-component',
  props: ['styled']
})

new Vue({
  el: '#app',
})
body {
  font-family: "Montserrat"
}

.card {
  border-radius: 8px;
  margin: 20px;
  padding: 30px 40px;
}

.first-component {
  background-color: #FFBF88;
  font-size: 16px;
  font-weight: bold;
}
.second-component {
  background-color: #C4E0F1;
  font-size: 12px;
  text-align: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>

<div id="app">
  <my-component styled="first-component"></my-component>
  <my-component styled="second-component"></my-component>
</div>



<template id="my-component">
  <div class="card" :class="styled">
      I'm the same component
  </div>
</template>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement