一、基础结构差异
1. 组件注册
- 语法糖:无需手动注册组件,直接引入即可使用
xml
<script setup>
import ChildComponent from './Child.vue'
</script>
传统写法 :需在 components
选项中显式注册
xml
<script>
import ChildComponent from './Child.vue'
export default {
components: { ChildComponent }
}
</script>
markdown
#### 二、Props/Emits 处理
**2. 接收 Props**
- **语法糖**:通过 `defineProps` 宏直接声明
传统写法 :通过 setup
函数参数接收
xml
<script>
export default {
props: ['msg'],
setup(props) {
// 使用 props.msg
}
}
</script>
3. 触发事件
- 语法糖 :通过
defineEmits
定义事件
xml
<script setup>
const emit = defineEmits(['update:value'])
emit('update:value', newValue)
</script>
传统写法 :通过 setup
第二个参数 context
触发
xml
<script>
export default {
setup(props, { emit }) {
emit('update:value', newValue)
}
}
</script>
三、暴露方法/属性
4. 子组件暴露内容
- 语法糖 :使用
defineExpose
显式暴露
xml
<script setup>
const childMethod = () => { /* ... */ }
defineExpose({ childMethod })
</script>
传统写法 :通过 return
或 expose
选项暴露
xml
<script>
export default {
setup() {
const childMethod = () => { /* ... */ }
return { childMethod } // 或使用 expose 选项
}
}
</script>
四、代码简洁性对比
5. 代码结构简化
- 语法糖 :省去
export default
、setup
函数和return
语句
xml
<script setup>
const count = ref(0)
</script>
传统写法:需完整结构2
xml
<script>
export default {
setup() {
const count = ref(0)
return { count }
}
}
</script>
五、性能与开发体验
- 编译优化:语法糖在编译阶段直接生成更高效的代码,减少运行时开销
- 类型推导:语法糖支持更好的 TypeScript 类型推断
- 生命周期 :两者均支持组合式 API 生命周期钩子(如
onMounted
)