Vue's Single-File Components (i.e., *.vue files, English Single-File Component, abbreviated as SFC) are a special file format that allows us to encapsulate a Vue component's template, logic, and styles in a single file.
In Vue3, you can use .vue files to create Single File Components (SFCs). This file contains the component's template, JavaScript code, and CSS styles.
Now we will delete all content from the example project created by the npm init vue@latest command (refer to (#)) in order to create our own simple webpage in Vue.
Before we start writing code, delete all content inside the , , and tags, as well as any attributes like setup or scoped.
Your App.vue file should now look like this:
## App.vue File:
At the same time, we can first clear the folders **assets** and **components** in the **src** directory. The files inside can be added and supplemented by ourselves later.
Modify the main.js file code to the following:
## main.js File Code:
import{ createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
Now we have created a simple project. Write the following code in the App.vue file:
## App.vue File Code:
{{ message }}
export default {
data() {
return {
message: 'Hello, !'
}
}
}
h1 {
color: blue;
}
In the above example, we defined a simple component containing a title. The component's template contains an
element, using Vue3's template syntax to bind the message attribute to the text content of this element.
The JavaScript part contains a data function that returns an object containing the message attribute, which we bound to the template.
Finally, the CSS style defines the title color as blue.
In the JavaScript part of the component, we used the new export default syntax, which allows us to export the component definition as a default object. In Vue3, we can use this syntax to define components without having to use the Vue.component function like in Vue2.
Visit **http://localhost:5173/**, the execution result of the above code is:
!(#)
### Using Components
After defining a component, we can use this component in other components.
To use a component, we need to create the component first. For example, the following example creates a **HelloTutorial.vue** component file in the **./src/components/** directory. The code is as follows:
## ./src/components/HelloTutorial.vue File Code:
{{ message }}
export default {
data() {
return {
message: 'Hello, !'
}
}
}
h1 {
color: red;
}
Then we introduce and define this component in the ./src/main.js file:
## ./src/main.js File Code:
import{ createApp } from 'vue'
import App from './App.vue'
import HelloTutorial from './components/HelloTutorial.vue'
const app = createApp(App)
app.component('hello-', HelloTutorial)// Custom tag
app.mount('#app')
In the parent component's template, we can introduce child components using custom tags, just like in the following App.vue file code:
## App.vue File Code
Visit **http://localhost:5173/**, the execution result of the above code is:
!(#)