LoginSignup
10
5

More than 3 years have passed since last update.

【Vue.js + TypeScript】コンポーネント間のデータやりとりについてのメモ

Last updated at Posted at 2019-11-20

概要

ちょっと夏休みとかちょっと冬休みとかあるとすぐ書き方を忘れるのでメモ

親→子にプロパティでデータを渡す(props)

Parent.vue
<template>
  <div class="content">
    <child :data="text" />
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import Child from "./Child.vue";

@Component({
  name: "parent",
  components: {
    Child
  }
})
export default class Parent extends Vue {
  text = "データだよ";
}
</script>
Child.vue
<template>
  <div class="content">
    {{ text }}
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Prop } from "vue-property-decorator";

@Component({
  name: "child"
})
export default class Child extends Vue {
  @Prop({ default: "" })
  text!: string;
}
</script>

子→親にイベントでデータを渡す(emit)

Parent.vue
<template>
  <div class="content">
    <child @handle-parent="childEvent" />
    {{ text }}
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import Child from "./Child.vue";

@Component({
  name: "parent",
  components: {
    Child
  }
})
export default class Parent extends Vue {
  text = "";

  childEvent(text) {
    this.text = text;
  }
}
</script>
Child.vue
<template>
  <div class="content">
    <button @click="handler('データだよ')" />
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";

@Component({
  name: "child"
})
export default class Child extends Vue {
  handler(text) {
    this.$emit("handle-parent", text);
  }
}
</script>

親→子のメソッドを呼び出す(refs)

Parent.vue
<template>
  <div class="content">
    <child ref="child" />
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import Child from "./Child.vue";

@Component({
  name: "parent",
  components: {
    Child
  }
})
export default class Parent extends Vue {
  $refs!: {
    child: Child
  }

  mounted() {
    this.$refs.child.hello();
  }
}
</script>
Child.vue
<template>
  <div class="content"> </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";

@Component({
  name: "child"
})
export default class Child extends Vue {
  hello() {
    alert("Hello!");
  }
}
</script>

子→親のメソッドを呼び出す(emit)

これはデータを渡すときと同じですね!

感想

暗記できません(⌒∇⌒)

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