概要
ちょっと夏休みとかちょっと冬休みとかあるとすぐ書き方を忘れるのでメモ
親→子にプロパティでデータを渡す(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)
これはデータを渡すときと同じですね!
感想
暗記できません(⌒∇⌒)