官术网_书友最值得收藏!

Defining and using the components

We will write our UI components in a new file:

  1. 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.

  1. 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>.

  1. 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.

主站蜘蛛池模板: 巴塘县| 常熟市| 通榆县| 炎陵县| 舟曲县| 中宁县| 小金县| 金湖县| 博客| 曲麻莱县| 房产| 阿拉尔市| 大港区| 个旧市| 沅江市| 江源县| 喀喇| 周宁县| 大姚县| 皋兰县| 台州市| 双峰县| 大连市| 潜江市| 西藏| 永嘉县| 南安市| 西林县| 宁远县| 安阳市| 广昌县| 福鼎市| 佳木斯市| 丰县| 米脂县| 城口县| 宜章县| 蓝田县| 西充县| 卢氏县| 响水县|