Vue 的响应式系统会自动追踪数据变化并更新视图。组件通过 props 接收数据,通过 emit 发送事件。
本节要点
- ref 适合基本类型,reactive 适合对象。
- computed 会根据依赖自动缓存计算结果。
- defineProps 和 defineEmits 用于组件通信。
代码示例
<script setup>
import { ref, computed } from "vue";
const price = ref(99);
const count = ref(2);
const total = computed(() => price.value * count.value);
const props = defineProps({ title: String });
const emit = defineEmits(["buy"]);
</script>
<template>
<h3>{{ props.title }}</h3>
<p>总价:{{ total }}</p>
<button @click="emit('buy', count)">购买</button>
</template>