全书目录

第三篇:Vue 完全指南 —— 新城区商业街宇宙

第八章:Props + Emits —— 总部下发规定,店铺回传消息

1 分钟 37 字 第 78 / 962 个阅读单元

Vue 组件之间的基本通信,仍然是:

  • 父传子:props
  • 子传父:emit
vue
<!-- Parent.vue -->
<script setup lang="ts">
import { ref } from 'vue';
import ShopCard from './ShopCard.vue';

const rent = ref(300);
</script>

<template>
  <ShopCard :rent="rent" @raise-rent="rent++" />
</template>
vue
<!-- ShopCard.vue -->
<script setup lang="ts">
const props = defineProps<{
  rent: number;
}>();

const emit = defineEmits<{
  (e: 'raise-rent'): void;
}>();
</script>

<template>
  <div>
    <p>当前租金:{{ props.rent }}</p>
    <button @click="emit('raise-rent')">申请涨租测试</button>
  </div>
</template>
text
父组件 state
   ↓ props
子组件展示
   ↓ emit
父组件修改 state
   ↓
props 再次下发