刷刷题43 (Vue3 语法糖(<script setup>)与传统写法对比及示例)

181 阅读1分钟

一、基础结构差异

1. 组件注册

  • 语法糖‌:无需手动注册组件,直接引入即可使用‌
<script setup>
import ChildComponent from './Child.vue'
</script>

传统写法‌:需在 components 选项中显式注册‌

<script>
import ChildComponent from './Child.vue'
export default {
  components: { ChildComponent }
}
</script>
#### 二、Props/Emits 处理**2. 接收 Props**-**语法糖**‌:通过 `defineProps` 宏直接声明‌

传统写法‌:通过 setup 函数参数接收‌

<script>
export default {
  props: ['msg'],
  setup(props) {
    // 使用 props.msg
  }
}
</script>

3. 触发事件

  • 语法糖‌:通过 defineEmits 定义事件‌
<script setup>
const emit = defineEmits(['update:value'])
emit('update:value', newValue)
</script>

传统写法‌:通过 setup 第二个参数 context 触发‌

<script>
export default {
  setup(props, { emit }) {
    emit('update:value', newValue)
  }
}
</script>

三、暴露方法/属性

4. 子组件暴露内容

  • 语法糖‌:使用 defineExpose 显式暴露‌
<script setup>
const childMethod = () => { /* ... */ }
defineExpose({ childMethod })
</script>

传统写法‌:通过 return 或 expose 选项暴露‌

<script>
export default {
  setup() {
    const childMethod = () => { /* ... */ }
    return { childMethod } // 或使用 expose 选项
  }
}
</script>

四、代码简洁性对比

5. 代码结构简化

  • 语法糖‌:省去 export defaultsetup 函数和 return 语句‌
<script setup>
const count = ref(0)
</script>

传统写法‌:需完整结构‌2

<script>
export default {
  setup() {
    const count = ref(0)
    return { count }
  }
}
</script>

五、性能与开发体验

  • 编译优化‌:语法糖在编译阶段直接生成更高效的代码,减少运行时开销‌
  • 类型推导‌:语法糖支持更好的 TypeScript 类型推断‌
  • 生命周期‌:两者均支持组合式 API 生命周期钩子(如 onMounted)‌