サイトアイコン 上尾市のWEBプログラマーによるブログ

「これからはじめるVue.js実践入門」の感想・備忘録3

「これからはじめるVue.js実践入門」の感想・備忘録2の続き

コンポーネント

new Vue()とコンポーネントの違い

グローバル登録とローカル登録

グローバル登録

<script>
Vue.component('my-hello', {
    template: '<p>グローバル登録されたコンポーネントです</p>',
  }
})
</script>

ローカル登録

<script>
const app = new Vue({
  el: '#app',
  components: {
    'my-hello2': {
      template: '<p>ローカル登録されたコンポーネントです。</p>',
    }
  },
})
</script>

プロパティ(Props)

キャメルケースで定義し、ケバブケースで属性として指定する。

<script>
Vue.component('my-hello', {
  template: '<p>testText:{{ testText }}</p>',
  props: ['testText'],
})
</script>
<!-- と定義し、以下で呼び出し。 -->
<my-hello test-text="これはプロパティです。"></my-hello>

属性値としてxxx="yyy"と指定した場合は、全て文字列として扱われる。

プロパティの値は変更してはいけない。

<script>
Vue.component('my-hello', {
  template: '<div><p>text:{{ text }}</p><p>testText:{{ testText }}</p><p>newTestText:{{ newTestText }}</p></div>',
  props: ['testText'],
  data: function () {
    return {
      text: 'グローバル登録されたコンポーネントです。',
      newTestText: this.testText,
    }
  },
  mounted: function() {
    this.newTestText = "warning"
  }
})
</script>

プロパティの型制限

<script>
Vue.component('my-hello2', {
  template: '<p>name: {{ name }} num: {{ num }} msg: {{ msg }}</p>',
  props: {
    name: {
      type: String,
      default: "hoge",
    },
    num: {
      type: Number,
      required: true,
    },
    msg: String
  }
}
</script>
<!-- と定義し以下で呼び出し。-->
<my-hello2 v-bind:num="88" msg="zzz"></my-hello2>

<!--
型だけ指定する場合は
name: String
だが、requiredまたはdefaultも指定する場合はオブジェクトとする。
name: {
  type: String,
  default: "hoge",
},

defaultが配列またはオブジェクトの場合は規定値を返却する関数とする。
user: {
  type: Object,
  default: function() {
    return {name: 'hoge'}
  }
},
-->

$emitメソッド

<!-- 親 -->
<my-hello v-on:plus="handleMyHelloPlus"></my-hello>
<p>count: {{ count }}</p>
<script>
{
  methods: {
  handleMyHelloPlus(num) {
    this.count += num;
  }
}
</script>

<!-- 子 -->
<script>
{
  template: `<button v-on:click="handleButtonClick">$emit</button>`,
  methods: {
    handleButtonClick() {
      this.$emit('plus', 2);
    }
  }
}
</script>

.native修飾子

スロット

スロット

呼び出し時にタグボディに指定した文字列を、コンポーネントのテンプレートに差し込むことができる。

定義
呼び出し

名前付きスロット

複数のスロットを埋め込む場合は名前付きスロットを利用する。

定義
呼び出し
<my-hello>
  <template v-slot:header><strong>スロットにより差し込まれたヘッダーです。</strong></template>
  <template v-slot:footer><strong>スロットにより差し込まれたフッターです。</strong></template>
</my-hello>
使い方

スコープ付きスロット

スロットを使って子コンポーネントの情報を取得することができる。

定義
呼び出し
使い方
モバイルバージョンを終了