技術ブログ

(技術系中心)基本自分用備忘録なので、あくまで参考程度でお願いします。

コンポーネント

コンポーネント

ページを構成するUIをコンポーネントで分ける componentは設計図のイメージ。

構成

HTMLベースのテンプレート
JavaScriptで書かれたロジック

名称付

ハイフンを一つ以上含むケバブケースを利用する必要あり。それ以外はNG

利用する理由

再利用ができる
メンテナンス性が上がる

グローバル定義

グローバルの場合は全てのインスタンスから利用できる

Vue.component('hello-component', {
    template: '<p>hello</p>'
})


new Vue({
  el: "#app",
})
<div id="app">
  <hello-component></hello-component>
  <hello-component></hello-component>
  <hello-component></hello-component>
</div>

--> helloと表示される

Vue - JSFiddle - Code Playground

ローカル定義

特定のvueインスタンス配下でしか利用しないとわかっているコンポーネントは、ローカルを利用する。

var helloComponent = {
    template: '<p>hello</p>'
}


new Vue({
  el: "#app",
  components: {
    'hello-component': helloComponent
  }
})
<div id="app">
   <hello-component></hello-component>
   <hello-component></hello-component>
   <hello-component></hello-component>
</div>

ーー>helloと3回表示 Vue - JSFiddle - Code Playground

参考: yusukelog.com

オプション

Vue.component('button-counter', {
    data: function() {
    return {
        count: 0
    }
  },
  template: '<button v-on:click="count++"> {{ count }}</button>'
})


var app = new Vue({
  el: "#app",
})
<div id="app">
  <button-counter></button-counter>
  <button-counter></button-counter>
  <button-counter></button-counter>
</div>

--> それぞれのcomponentでcountが出来る

Vue - JSFiddle - Code Playground