LoginSignup
1
0

More than 1 year has passed since last update.

【Vue】CompositionAPIでcomputed, data, method

Posted at

data

Vue2で定義していたdataプロパティ内の変数はcompositionAPIからはreactive又はrefの中に定義する

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  setup() {
    const state = reactive({ hoge: 'huga' })

    return { state }
  }
})
</script>

型定義する場合

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  setup() {
    const state = reactive<string>({ hoge: 'huga' })

    return { state }
  }
})
</script>

computed

Vue2ではcomputedプロパティ内で記述していたメソッドはCompositionAPIではかなり異なる

<template>
  <div>{{fullName}}</div>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue'

interface UserName {
  firstName: string
  lastName: string
}

export default defineComponent({
  setup() {
    const state = reactive<UserName>({
      firstName: 'hoge',
      lastName: 'huga'
    })

    const fullName = computed(():string => state.firstName + state.lastName)

    return { state, fullName }
  }
})
</script>

method

Vue2ではmethodプロパティ内でメソッド定義していたがCompositionAPIでは異なる

<template>
  <div>
    <button @click="clickEvent()">Click Me!<button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  setup() {
    const clickEvent = ():void => alert('Clickしたよ!')

    return { clickEvent }
  }
})
</script>

関数型でかけていい感じ!

Vue+TypeScriptの公式

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