コンポーネントをちょっと使ってみました

コンポーネントは Vue.js の最も強力な機能の1つです。基本的な HTML 要素を拡張して再利用可能なコードのカプセル化を助けます。
Vue.jsドキュメント

基本的な使い方

HTML

<div id="demo1">
  <sample-component></sample-component>
</div>

Vue.js

var SampleComponent = Vue.extend({
  template: `<div>コンポーネントテスト</div>`
})
new Vue({
  el: "#demo1",
  components: {
    'sample-component': SampleComponent
  }
})

Props

HTML

<div id="demo1" class="section">
  <sample-component msg="hello!"></sample-component>
</div>

Vue.js

var SampleComponent = Vue.extend({
  template: `<div>コンポーネントテスト{{msg}}</div>`,
  props: ['msg']
})
new Vue({
  el: "#demo1",
  components: {
    'sample-component': SampleComponent
  }
})

動的なProps

先ほどのJavaScriptはそのままにHTMLを以下のように書き直します。

<div id="demo1">
  <input type="text" v-model="message">
  <sample-component v-bind:msg="message"></sample-component>
</div>

デモサイト

Tweet
このエントリーをはてなブックマークに追加
Pocket