vue.js入門_17_コンポーネント

by s9iwork

HTML

<div id="app">
  <h2>グローバルコンポーネント</h2>
  <hello-component></hello-component>
  <hello-component></hello-component>
  <hello-component></hello-component>

  <h2>ローカルコンポーネント</h2>
  <hello-local-component></hello-local-component>
  <hello-local-component></hello-local-component>

  <h2>コンポーネントの命名規則</h2>
  <hello></hello>
  <hello_component></hello_component>

  <h2>dataプロパティを利用する</h2>
  <button-counter></button-counter>
  <button-counter></button-counter>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.22/dist/vue.js"></script>

CSS

#app {
  max-width: 500px;
}

h2 {
  font-size: 1.2rem;
}

h2::before {
  content: "■";
}

.container {
  display: flex;
}

.container>div {
  margin-right: 2rem;
}

JavaScript

// グローバルコンポーネント
Vue.component('hello-component', {
  template: '<p>Hello</p>'
})

// ローカルコンポーネント
var localComponet = {
  template: '<p>Hello local</p>'
}

// コンポーネントの命名規則
Vue.component('hello', {
  template: '<p>エラーにはならない</p>'
})
Vue.component('hello_component', {
  template: '<p>エラーにはならない</p>'
})

// dataプロパティを利用する
Vue.component('button-counter', {
  data: function() {
    return {
      count: 0
    }
  },
  template: '<button v-on:click="count++">{{count}}</button>'
})

new Vue({
  el: '#app',
  data: {
    message: 'hogehoge',
  },
  components: {
    'hello-local-component': localComponet
  }
})