Single File Components

Published on Sep 11, 2022

Files with .vue extension that are loaded by the Vue Router.

Anatomy

3 sections: template, script & style.

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
a {
  color: #42b983;
}
</style>

Routing

src/router/index.js

import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";

const routes = [
  {
    path: "/",
    name: "home",
    component: HomeView,
  },
  ...
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

export default router;

Components can also be imported directly:

...
const routes = [
  ...
  {
    path: "/about",
    name: "about",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
  },
  ...
];
...

Data & Props

`data` contains the state that is self-contained inside the components. `props` is the state that is passed in.

export default {
  name: "Greet",
  data() {
    return {
      greeting: "Hello"
    }
  },
  props: {
    name: String,
  },
};

A value for name can be passed in:

<Greet name="Paul"></Greet>

Events

...

Emits

...

Import "Subcomponents"

components/Product.vue

export default {
  name: "Product",
  props: {
    product: Object,
  },
};

components/Catalogue.vue

<template>
  <div>
    <product v-for="product in products" :key="product.id" :product="product"></product>
  </div>
</template>
<script>
import Product from '@/components/Product.vue'

export default {
  name: "Catalogue",
  props: {
    products: Array,
  },
  components: {
    Product
  }
};
</script>

Best Practices

...