LoginSignup
17
16

More than 3 years have passed since last update.

Vue3の基本構文②

Last updated at Posted at 2020-10-18

Vueの構文についてコードベースで簡単にまとめます。
今回は以下の三つです。
ちなみに前回はこちら

  • eventハンドリング
  • class & styleバインディング
  • computedプロパティー

eventハンドリング

index.html
<div class="cart">Cart({{ cart }})</div>
...
<button class="button">Add to Cart</button>
main.js
data() {
  return {
    cart: 0,
    ...
  }
}

buttonをクリックした際にcartの値を増やしたい場合、以下のように書くことができます。

インラインで書く(処理がシンプルな場合)

index.html
<button class="button" v-on:click="cart += 1">Add to Cart</button>

処理がシンプルな場合この様にインラインで書くことができますが、より複雑な場合は以下の様にmethodsを使います。

メソッドを使って書く(基本的にこちらを使うことが多いです)

index.html
<button class="button" v-on:click="addToCart">Add to Cart</button>

buttonをクリックすると、addToCartメソッドが呼ばれます。

main.js
const app = Vue.createApp({
  data() {
    return {
      cart: 0,
      ...
    }
  },
  methods: {
    addToCart() {
      this.cart += 1
    }
  }
})

methodsオプションの中にインラインで書いた処理と同じロジックのaddToCartメソッドを追加します。ここで注意したいのが、methodsオプションの中ではthis.cartを使ってVueインスタンスdataにあるcartを参照します。

ショートカット

index.html
<button class="button" @click="addToCart">Add to Cart</button>

v-bind:のようにv-on@で短縮形で書くことができます。

class & styleバインディング

index.html
<div 
  ...
  class="green" >
</div>

greenクラスのCSSを要素にバインディング

index.html
<div 
  ...
  :style="{ color: green }" >
</div>

要素に直接スタイルをバインディング

computedプロパティ

main.js
const app = Vue.createApp({
  data() {
    return {
      firstName: '太郎',
      lastName: '田中'
      ...
    }
  },
  computed: {
    fullName: function () {
        return this.firstName + ' ' + this.lastName
    }
  }
})
index.html
<h1>{{ fullName }}</h1>

Vueインスタンスdataのプロパティからcomputedプロパティを生成することができます。computedプロパティは一度アクセスされると内部メモリに保存され高速で処理ができます。そして、computedプロパティ(fullName)が依存しているdataプロパティー(firstNmae,lastName)が変更された場合、再度関数が評価されfullNameが更新されます。

17
16
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
17
16