5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VueとTypeScript emitの書き方!

5
Last updated at Posted at 2020-01-15

emitとは

まずemitとはどんな時に使うのか。
子コンポーネントが親コンポーネントにデータとか渡したい。
そんな時にemitを使います。

親コンポーネントと子コンポーネント、どっちがどっち?

わかる人は飛ばしてください。
親コンポーネントと子コンポーネントがどっちかがわからなくなっている人!
(↑私も最初そうでした。。)

コンポーネントを呼んでいる方が親 (importする方)。
呼ばれている方が子供。

emitをTypeScriptでかく!

大事なところは
子供から渡すところと親が受け取るところ!
this.emit()の部分と@sample=""のところを良くみてね。

⬇︎子コンポーネント

<template>
<v-btn text v-on:click="buttonClick"></v-btn>
</template>
<script>
import { Component, Vue, Prop } from "vue-property-decorator";
@Component()
export default class StackedForm extends Vue {
private buttonClick(): void {
         // ⬇︎親の@マークの名前
    this.$emit("sample", "aaa");
               // ⬆︎引数指定できる!
  }
}
</script> 

⬇︎親コンポーネント

                       // ⬇︎子から受け取る
<stack-form :text-fields="textFields" @sample="emitChan"></stack-form>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import StackForm from "@/components/organisms/forms/StackedForm.vue";
@Component({
  components: {
    StackForm
  }
})
export default class Login extends Vue {
      // ⬇︎子から引数でデータ受け取って実行とかできる!
  private emitChan(value: any): void {
    console.log(value);
  }
}
</script>

簡単にいうと!

emitの第1引数に@の名前がきて第2引数からはemitChanに引数で渡されるよ!
ちなみに第3引数以降も指定して渡しても大丈夫!

はてなブログもやってます

はてなブログのVue系⬇︎ぜひご覧ください!
https://taitoajiki.hatenablog.com/archive/category/Vue

5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?