開発規模が大きくなり複雑になってくるので同じ処理をまとめる。
componentを用いて処理をまとめる
コンポーネント作成方法は、「グローバルに登録」「ローカルに登録」の2種類ありますが、今回はローカルに登録する方法を採用する。
書式
<script> var コンポーネントのオブジェクト名 = { template: 'HTML部分' } new Vue({ el: '#app' components: { 'コンポーネントのタグ名': コンポーネントのオブジェクト名 } }) </script>
実装
Hello World! と表示するだけのコンポーネントを作成し、5つ表示する。
手順
<div id="app"> <hello-component></hello-component> <hello-component></hello-component> <hello-component></hello-component> <hello-component></hello-component> <hello-component></hello-component> </div> <script> var HelloComponent = { template: '<p class="hello-comp">Hello World!</p>' } new Vue({ el: '#app' components: { 'hello-component': HelloComponent } }) </script> <style> .hello-comp { width: 120px; background-color: #defaba; border: solid; border-color: #69686b; border-radius: 8px; padding: 8px; } </style>