LoginSignup
3
1

More than 5 years have passed since last update.

Vue.jsの応用について-コンポーネント

Last updated at Posted at 2019-04-12

完成イメージ

スクリーンショット 2019-04-12 21.42.27.png

ソースコード

ドットインストールを参考にしてます。
https://dotinstall.com/lessons/basic_vuejs_v2
※プレミアム会員のみ閲覧可能

↓細かい説明はコメントアウトでまとめてます↓

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>My Sample Vue App2</title>
  <link rel="stylesheet" href="css/styles.css">
</head>
<body>

  <div id="app">
    <p>Total Likes {{total}}</p>
    <!-- messageでcomponentにカスタム属性として値を渡す -->
    <like-component message="Like" @increment="incrementTotal"></like-component>
    <like-component message="Awesome" @increment="incrementTotal"></like-component>
    <like-component message="Great" @increment="incrementTotal"></like-component>
    <like-component @increment="incrementTotal"></like-component>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="./js/main.js"></script>
</body>
</html>
main.js
//プロパティの設定には、;はつけない
(function(){
  'use strict';

  // コンポーネント(component)は名前付きの再利用可能なVueインスタンス
  // 独自のタグを書くことができる
  //extendで囲って、中身の定義をtemplateで書く。
  //templateに書ける要素は1つのみ。複数書きたい場合は<div>とはで親要素を作ってあげる。

  let likeComponent = Vue.extend({
    //""の中は''でないとエラーになる
    template: "<button @click='countUp'>{{message}}{{count}}</button>",
    //配列でキーを受け取りますとしている。
    // props: ["message"],
    //propsにデフォルト値や型を指定するには、オブジェクトとして書く必要あり。
    props: {
      message:{
        type: String,
        default: "Like"
      }
    },
    // dataをコンポーネント定義の中で使用する場合は、Functionタイプのみ受け付ける
    data: function(){
    //設定したプロパティをreturnする時は{}で囲む必要あり。  
      return{
        count: 0
      }
    },
    methods: {
      countUp: function(){
      //プロパティはthisで取得できる
        this.count++;
      //componentから親要素に対してincrementというカスタムイベントを発火させるには$emitを使う。
      //view側で@increment="incrementTotal"を仕込む。
      //親要素にデータを渡したい時は、このようにする。
      //イベントの発火のみcomponent側でやり、data,methods設定は親要素で行う。
        this.$emit("increment");
      }
    }
  })

  const vm = new Vue({
    el: "#app",
    // componentsの登録。#appに対して、このcomponentを使うよ、と宣言。
    components: {
      //like-component(タグで使う)の中身はlikeComponentというオブジェクトとする
      // 末に;つけるとエラーになる。
      "like-component": likeComponent
    },
    data: {
      total: 0
    },
    methods: {
      incrementTotal: function(){
        this.total++;
      }
    }
  })
})()
3
1
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
3
1