Last updated on October 9, 2022
Vue JS templates are HTML-based, and its core system allows declarative bind render data to the DOM using simple template syntax. Vue.js compiles javascript code and optimizes it for the browser. In this article, we will create a single file component. Let’s get started.
Create a file in the source (SRC) directory with .vue
and open it in the HTML editor. Then paste the below code.
<template>
<div>
<span class="name">Hello {{name}}!</span>
</div>
</template>
<script>
export default {
data() {
return {
name: 'Jhon'
}
}
}
</script>
<style scoped>
.name{color:#ff0000}
</style>
In the above example, as you can see template tag starts and closes. All the logic is inside the template tag.
<span>Hello {{name}}!</span>
In the above example span has the text “Hello {{name}}”
. The name variable with curly braces shows the name property value from the data()
method. In the browser, the full text will be “Hello John”
.
An important point is that the <template>
tag accepts only one child element. That’s why another child element DIV created for all HTML code. Vue data can be shown using curly braces {{}}
which are called Mustache syntax.
In the script tag, the export default object has a data()
method that returns the name property which can be shown in the HTML tag span.
In the single file component, we can embed the style sheet as well. In the above example, a <style>
tag opened with scoped attribute which means all style classes are component-specific. It can be used for only this component. it will not impact the same class in other components.
In this article, we explained how to create a single file component through template syntax. If you would like to learn more about it then check out the Vue.js page.