Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Vue.js 入門 vol.6 コンポーネント 後半

参考サイト

https://jp.vuejs.org/v2/guide/components.html#動的コンポーネント

動的コンポーネント

  • コンポーネントの切り替え: componentタグと、isによるcomponentの指定で実装可能。
var vm = new Vue({
  el: '#example',
  data: {
    currentView: 'home'
  },
  components: {
    home: {},
    posts: {},
    archive: {}
  }
})
<component v-bind:is="currentView">
  <!-- vm.currentview が変更されると、中身が変更されます! -->
</component>
var Home = {
  template: '<p>Welcome home!</p>'
}

var vm = new Vue({
  el: '#example',
  data: {
    currentView: Home
  }
})
  • keep-alive: 切り替えられたコンポーネントの状態保持のためには、keep-aliveタグを使う。
<keep-alive>
  <component :is="currentView">
      <!-- 非活性になったコンポーネントをキャッシュします! -->
  </component>
</keep-alive>

その他

再利用可能なコンポーネントの作成

  • Vue ComponentのAPIは以下の3つ

  • v-bind, v-on の省略記法を使うと見やすい。

<my-component
  :foo="baz"
  :bar="qux"
  @event-a="doThis"
  @event-b="doThat"
>
<img slot="icon" src="...">
<p slot="main-text">Hello!</p>
</my-component>

コンポーネントの参照

<div id="parent">
  <user-profile ref="profile"></user-profile>
</div>
// 親のコンストラクタ関数を定義
var parent = new Vue({ el: '#parent' })
// 親のコンテンツで、refでidを振った子コンポーネントのインスタンスへのアクセスß
var child = parent.$refs.profile

非同期コンポーネント

  • このあたりは、普通のjavascriptの解説を見る必要があるな。さっぱりわからん。ファクトリ関数

https://jp.vuejs.org/v2/guide/components.html#非同期コンポーネント

Vue.component('async-example', function(resolve, reject) {
  // コンポーネント定義を resolve コールバックで渡す
  setTimeout(function(){
    resolve({
      template: '<div>I am async!</div>'
    })
  }, 1000)
})

まとめ

  • 基本的な文法は、javascriptに近いので、javascriptをちゃんと理解している必要はあるな。
  • あとは、作りながら勉強していく感じかな〜。