6
5

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 1 year has passed since last update.

vue3覚書(props, emit, computed, ref)

Posted at

Props

親から子へ値を渡す

親コンポーネント

  • props名から値を渡す
<script setup lang="ts">
import show from "./components/show.vue";
</script>

<template>
  <show message="aiueo" />
</template>

子コンポーネント

  • 配列、Mapでも渡せる
  • messageがProps名
<script setup lang="ts">
import { defineProps } from "vue";

const props = defineProps({
  message: {
    type: String,
    default: '',
  },
});
</script>

<template>
  <div>
    {{ props.message }}
  </div>
</template>

emit

  • 子から親に値を渡す
  • App.vue(props) → Hello.vue(emit) → App.vue のような流れ

親コンポーネント

<script setup lang="ts">
import Hello from "./components/Hello.vue";

const testFn = (testInput: string) => {
  console.log(testInput)
}
</script>

<template>
  <Hello @emitTest="testFn"/>
</template>

子コンポーネント

 <script setup lang="ts">
import { defineEmits } from "vue";
const emit = defineEmits(["emitTest"])

const testFn = () => {
  emit('emitTest', "aiueo")
}
</script>

<template>
  <div>
    <button @click="testFn">call emit</button>
  </div>
</template>

computed

  • 処理や計算などを別だしできる
<script setup lang="ts">
import { computed } from "vue";

const total = computed(() => {
  return Math.round(10 * 30);
});
</script>

<template>
  <div>
    <p>{{ total }}</p>
  </div>
</template>

<style scoped></style>

ref

  • reactiveな値を扱うことができる
  • reactive = 変数と思っていい
<script setup lang="ts">
import { ref } from "vue";

const count = ref(0);

const increment = () => {
  count.value++;
};
</script>

<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">increment</button>
  </div>
</template>

<style scoped></style>
6
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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?