プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

Vue.js Componentと$emitのサンプルコード

■Vue.jsのComponentと$emitのサンプルコード
 
【HTMLファイル】


<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>Component emit</h1>
    <hr>
    <div id="app">
      <h3>Total:{{ total }}</h3>
      <!-- text=""でコンポーネントの表示名を決定 -->
      <!-- コンポーネントの「countUp」メソッド時に$emit()で「totalUp」メソッドが呼び出される -->
      <custom-button text="JavaScripit" @increment="totalUp"></custom-button>
      <custom-button text="Vue.js" @increment="totalUp"></custom-button>
      <!-- text=""が無い時はコンポーネントの「props」のdefaultで設定した文字列を表示 -->
      <custom-button @increment="totalUp"></custom-button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="main.js"></script>
  </body>
</html>

 
【JavaScriptファイル】


(() => {
  'use strict';

  let customButton = Vue.extend({
    template: '<div><button @click="countUp">{{ text }} {{ count }}</button></div>',
    // 「props」でコンポーネントに表示する名前を設定
    props: {
      text: {
        type: String,
        default: 'default'
      }
    },
    data: function(){
      return {
        count: 0
      }
    },
    methods: {
      countUp: function(){
        this.count++;
        // $emit()で「increment」をキーにイベント発火
        this.$emit('increment');
      }
    }
  });

  let vm = new Vue({
    el: '#app',
    components: {
      'custom-button': customButton
    },
    data: {
      total: 0
    },
    methods: {
      totalUp: function(){
        this.total++;
      }
    }
  });
})();