n How to use single file components in Vue.js | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

Single File Components allow us to define the HTML/CSS and JS of a component all within a single .vue file.

A single-file component is composed of three parts:

  • The <template> section which contains the component’s markup in plain HTML.
  • The <script> section which contains all the JS logic within that component.
  • The <style> section which contains all the component styles.

Here’s an example of a single-file component given the name of HelloWorld:

  <div class="hello-world">
    <h2>{{ getGreeting }}</h2>
    <p>This is the Hello World component.</p>

export default {
  name: 'HelloWorld',
  data () {
    return {
      reversedGreeting: '!dlrow olleH'
  computed: {
    getGreeting() {
      return this.reversedGreeting

<style scoped>
.hello-world {
  width: 100%;
  text-align: center;
  • The <template> of the HelloWorld component displays the value of the getGreeting computed property declared in the <script> section as well some static text.
  • The getGreeting computed property simply reverses the reversedGreeting data property to return “Hello World!”.
  • The <style> section of the component has the scoped attribute which dictates the styles declared in the component will be applied to this and only this component.


Though the structure of a single-file component may look different, everything we’ve discussed thus far with regards to instance/component properties remains the same. We’re able to use all the properties a Vue instance component contains like datamethodscomputed properties, lifecycle hooks, etc.

The main advantage to using single-file components is how we’re able to neatly define the markup, logic, and styles of a component all within a single file. By building our application in a module-based setting (e.g. with Webpack), we’re also able to take advantage of modules to break our application (and components!) to smaller discrete pieces.


Defining and Using Single-File Components

We can use single-file components easily with the Vue CLI. To do this, we just create a folder, go into it, and then run:

npx vue create .

and select the default options.

Then we should get a starter app with single-file components that we can change.

The single-file components have the .vue extension.

When we create an app with Vue CLI, we get App.vue and components/HelloWorld.vue .

They have the structure:


Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook