- Vue.js 2 Web Development Projects
- Guillaume Chau
- 218字
- 2021-07-02 22:34:32
Defining and using the components
We will write our UI components in a new file:
- Create a components folder and a new ui.js file inside it. Include it in the main index.html page, just before the main script:
<!-- Scripts -->
<script src="utils.js"></script>
<script src="cards.js"></script>
<script src="state.js"></script>
<script src="components/ui.js"></script>
<script src="main.js"></script>
In this file, we will register our components, so it's important that the main Vue instance is created afterward, and not before. Else, we would get errors of components not being found.
To register a component, we can use the global Vue.component() function. It takes two arguments; the name under which we register the component, and its definition object, which is using the exact same options as the Vue instance that we already know.
- Let's create the top-bar component in the ui.js file:
Vue.component('top-bar', {
template: `<p class="top-bar">
Top bar
</p>`,
})
Now, we can use the top-bar component in our templates, just like any other HTML tags, for instance, <top-bar>.
- In the main template, add a new top-bar tag:
new Vue({
// ...
template: `<p id="#app">
<top-bar/>
</p>`,
})
This template will create a new top-bar component and render it inside the #app element, using the definition object we just defined. If you open the devtools, you should see two entries:

Each one is a Vue instance--Vue actually created a second instance using the definition we provided for the top-bar component.
- 微服務與事件驅動架構
- Vue.js入門與商城開發實戰
- PyTorch Artificial Intelligence Fundamentals
- 算法大爆炸:面試通關步步為營
- 從0到1:HTML+CSS快速上手
- UML 基礎與 Rose 建模案例(第3版)
- 學習OpenCV 4:基于Python的算法實戰
- HTML5從入門到精通(第4版)
- Learning Unreal Engine Android Game Development
- Django 3.0入門與實踐
- Spring Boot實戰
- Android應用開發實戰
- Android Sensor Programming By Example
- JavaEE架構與程序設計
- Developing Java Applications with Spring and Spring Boot