How to use a single-file component in Vue.js?

To use a single-file component in Vue.js, we have to set up Vue Loader for parsing the file (It is done automatically as a part of a webpack building pipeline). It also supports non-default languages such as Sass or HTML templating languages with pluggable pre-processors.

To use a single-file component in Vue.js, follow these steps:

  1. Create a .vue file: This file will contain your component’s template, script, and styles. You can create this file manually or through Vue CLI.
  2. Define the template: Within the .vue file, define the HTML template using the <template> tag. This is where you’ll write your component’s markup.
  3. Define the script: Use the <script> tag to define the JavaScript logic for your component. This includes data properties, methods, computed properties, and lifecycle hooks.
  4. Define the styles (optional): If you need component-specific styles, you can include them within the <style> tag. Vue supports CSS, SCSS, and other pre-processors.
  5. Export the component: Export the component using the export default statement at the end of the .vue file.

Here’s an example of a simple Vue single-file component:

html
<template>
<div>
<h1>{{ message }}</h1>
<button @click="reverseMessage">Reverse Message</button>
</div>
</template>

<script>
export default {
data() {
return {
message: 'Hello Vue!'
}
},
methods: {
reverseMessage() {
this.message = this.message.split('').reverse().join('');
}
}
}
</script>

<style scoped>
h1 {
color: blue;
}
</style>

In this example:

  • The <template> section defines the HTML structure of the component.
  • The <script> section defines the JavaScript logic, including the component’s data and methods.
  • The <style> section defines the component’s styles, scoped to affect only this component.

To use this component in another Vue file or in your Vue application, you would import it like any other JavaScript module:

javascript
<template>
<div>
<custom-component></custom-component>
</div>

</template>

<script>
import CustomComponent from './CustomComponent.vue';

export default {
components: {
CustomComponent
}
}
</script>

<style>
/* Styles for this component */
</style>

Make sure to replace './CustomComponent.vue' with the correct path to your component file.