Skip to content

defineProps、defineEmits、defineExpose

  • defineProps用来父子组件之间数据传递
  • defineEmits用来定义组件事件
  • defineExpose暴露给父组件的方法或属性

1、defineProps

<!-- Parent.vue -->
<template>
  <div>
    <Counter :initialCount="count" />
  </div>
</template>

<script  setup>
import { ref } from 'vue';
import Counter from './Counter.vue';

const count = ref(100);
</script>


<!-- Counter.vue -->
<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

// 定义属性
const props = defineProps({
  initialCount: {
    type: Number,
    required: true
  }
});

// 使用属性
const count = ref(props.initialCount);

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

2、defineEmits

<!-- Parent.vue -->
<template>
  <div>
    <Counter :initialCount="count" @update:count="handleCountUpdate" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import Counter './Counter.vue'

const count = ref(100)

function handleCountUpdate(value) {
  console.log(value)
}
</script>


<!-- Counter.vue -->
<template>
  <div>
    <p>{{ count }}</p>
    <button @click="handleIncrement">Increment</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

// 定义属性
const props = defineProps({
  initialCount: {
    type: Number,
    required: true
  }
});

// 定义事件
const emit = defineEmits(['update:count']);

const count = ref(props.initialCount);

function handleIncrement() {
  count.value++;
  emit('update:count', count.value);
}
</script>

3、defineExpose

<!-- Parent -->
<template>
  <Counter ref="counter" :initialCount="10" @update:count="handleCountUpdate" />
  <button @click="resetCounter">Reset Counter</button>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import Counter from './Counter.vue';

const counter = ref(null);

function handleCountUpdate(value) {
  console.log(value);
}

function resetCounter() {
  counter.value.reset();
}
</script>


<!-- Counter.vue -->
<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

// 定义属性
const props = defineProps({
  initialCount: {
    type: Number,
    required: true
  }
});

// 定义事件
const emit = defineEmits(['update:count']);

const count = ref(props.initialCount);

function increment() {
  count.value++;
  emit('update:count', count.value);
}

function resetCount() {
  count.value = props.initialCount;
}

// 暴露方法
defineExpose({
  reset: resetCount
});
</script>