LoginSignup
1
0

More than 1 year has passed since last update.

Vue.js コンポーネント検証

Last updated at Posted at 2022-09-26

どうも、豚野郎です。
今回はコンポーネントを使ってみようと思います。

今回もソースの動きを見ながらの検証です。
ドットインストールのソースを参考にしています。
(プログラムは異なります)

1. コンポーネントの呼び出し

内容は、ボタンをクリックすると、ボタン横数字とTotalの数がカウントされていくものです。

js/main.js
(function() {
    'use strict';

    let childComponent = Vue.extend({
        props: {
            message: {
                type: String,
                default: 'button'
            }
        },

        data: function() {
            return{
                count: 0
            }
        },

        template: '<button @click="countUp">{{ message }} {{ count }}</button>',

        methods: {
            countUp: function() {
                this.count++;
                this.$emit('increment');
            }
        }
    });

    let app = new Vue({
        el: '#app',
        components: {
            'child-component': childComponent
        },

        data: {
            total: 0
        },

        methods: {
            incrementTotal: function() {
                this.total++;
            }
        }
    });
})();
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Vue</title>
</head>
<body>
    <div id="app">
        <p>Total: {{ total }}</p>
        <child-component @increment='incrementTotal'></child-component>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="js/main.js"></script>
</body>
</html>

【ポイント】
extend
サブクラスを作成する時に使います。

props
propsで親コンポーネントから子コンポーネントに渡せる。
(上記のプログラムでは行っていない)

・コンポーネントのdataは関数で返すルール。

this.$emit
今回はイベントの発火(index.html)。
他にも使い道がある(?)みたいなので、別の記事に今後書きます。
(今回はコンポーネントの検証のため)

componentsの左の記載箇所はhtmlと同じにする。

・この場合、イベントを発火する際、htmlにも@increment='incrementTotal’の記載が必要。
(incremetの箇所は任意で決められる)

4. 親コンポーネントから子コンポーネントへのデータ渡し

以下のサイトを参考にさせて頂きます。
参考:http://www.code-magagine.com/?p=5939

js/main.js
// 親コンポーネント
Vue.component('comp-parent', {
  template: '<div><h1>componentの親</h1><comp-child one="たけし" two = "たろう"/></div>'
})
 
// 子コンポーネント
Vue.component('comp-child', {
  template: '<p>componentの子:{{ one }}と{{ two }}</p>',
 
  //親から受け取る属性名
  props: ['one', 'two']
})
 
new Vue({
  el: '#app'
})
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Vue</title>
</head>
<body>
    <div id="app">
        <comp-parent></comp-parent>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="js/main.js"></script>
</body>
</html>

propsに親から受け取る属性名を記載します。
属性名は自分で決まられます。
また、中をカンマ区切りすれば複数指定できました。

検証したところ「たけし」と「たろう」が表示されました。

3. 感想

まだわからないことが多いので学習していきます。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0