0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Web素人がVueのtutorialをやってみる その2 (Step5/15 ~ Step6/15 まで)

Posted at

概要

前回に引き続きVueのチュートリアルをやってみます。今回はStep5からの続きです。
今回はポモドーロを試しているので変なところで終わるかも…

Step5

双方向バインディングについて

データバインディング

参考
UIの変更とデータを同期させる仕組み。
データからUIへの反映を認めるが逆は認めないのが単方向バインディング
両方向の反映を認めるのが双方向バインディング
後者はシンプルだが拡張性に乏しく、前者がその逆。
Vueは前回のv-bindv-onを併用することで双方向バインディングが実装できる。

双方向バインディングの構文は下記の通り。単体のタグの中にv-bindv-onが同居している。

<input :value="text" @input="onInput">

上記のシンタックスシュガーとしてv-modelディレクティブが用意されている。

<input v-model="text">

これを使った場合、HTML要素ごとに規定のイベントがハンドルされる。
テキストのinputなら@input, <input type="checkbox">なら@changeなど。

Step5 実践

以下をv-modelを使ってリファクタする。

Step5.vue
<script>
export default {
  data() {
    return {
      text: ''
    }
  },
  methods: {
    onInput(e) {
      this.text = e.target.value
    }
  }
}
</script>

<template>
  <input :value="text" @input="onInput" placeholder="Type here">
  <p>{{ text }}</p>
</template>

リファクタ後は下記
onInputメソッドまで省略されているところがポイント!

Step5-Ans.vue
<script>
export default {
  data() {
    return {
      text: ''
    }
  }
}
</script>

<template>
  <input v-model="text" placeholder="Type here">
  <p>{{ text }}</p>
</template>

Step6

条件付きレンダリングについて

v-ifディレクティブ

v-ifディレクティブで条件付きレンダリングが可能。

<h1 v-if="awesome">Vue is awesome!</h1>

awesomeプロパティがTruthyなら描画される。

Truthy : 真値とみなせる値のこと。Falsyな値を除く全ての値はTruty
Falsy : JSで偽値として定義されている値。0, "", null など

v-else-ifv-else の条件も作成できる。

<h1 v-else>Oh no 😢</h1>

Step6実践

Step6.vue
<script>
export default {
  data() {
    return {
      awesome: true
    }
  },
  methods: {
    toggle() {
      this.awesome = !(this.awesome)
    }
  }
}
</script>

<template>
  <button @click="toggle">Toggle</button>
  <h1 v-if="awesome">Vue is awesome!</h1>
  <h1 v-else>Oh no 😱</h1>
</template>

結果は下図。ボタンをクリックするごとに表示が変わる。

image.png

image.png

番外 FizzBuzz

作れる気がしたのでやってみます。

FizzBuzz.vue
<script>
export default {
  data() {
    return {
      count: 0
    }
  },
  methods: {
    increment() {
      this.count++
    },
		reset() {
      this.count = 0
    }
  }
}
</script>

<template>
  <button @click="increment">Count : {{count}}</button>
  <button @click="reset">Reset</button>
  <h1 v-if="count % 15 == 0">FizzBuzz</h1>
  <h1 v-else-if="count % 3 == 0">Fizz</h1>
  <h1 v-else-if="count % 5 == 0">Buzz</h1>
  <h1 v-else>{{count}}</h1>
</template>

結果
image.png
動きました。ちょっとおもしろい。

続く

ちょうどポモドーロのタイマーが鳴ったので今回はここまで😊
次回に続きます。多分…。

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?