文章目录
-
- 一、先一句话总纲
- [二、先讲最原始的:setup() 函数](#二、先讲最原始的:setup() 函数)
- [三、再讲现在主流:<script setup>](#三、再讲现在主流:<script setup>)
- 四、两者功能对比(最关键)
- 五、最核心区别(背这一段就够)
- 六、你能立刻记住的超级口诀
- 七、我再用最通俗的话总结一遍
- 八、注册(components)不能写在setup函数里
一、先一句话总纲
javascript
- setup():Vue3 原来的原始写法,手动挡,要写 return,麻烦。
```javascript
- <script setup>:官方给的语法糖(简写版),自动挡,不用 return,代码更少,现在全都用这个。
二、先讲最原始的:setup() 函数
你就把它理解成:
组件的入口函数,比 beforeCreate 还早执行。
- 里面没有 this
this = undefined
不能用 this.$refs、this.message 之类。
- 接收两个参数
javascript
js
setup(props, context) {
}
- props:父组件传过来的值(响应式,但不能改)
- context:里面有 emit、attrs、slots
- 必须 return!
你在 setup 里定义的变量、方法,
不 return,模板就看不见!
javascript
js
setup() {
const count = ref(0)
return { count } // 不 return 模板用不了
}
缺点
麻烦、啰嗦、要写一堆重复代码。
三、再讲现在主流:
它就是:
Vue 帮你自动把代码塞进 setup() 里,还自动 return。
- 不用写 return
你定义啥,模板直接用:
vue
javascript
<script setup>
const count = ref(0)
</script>
javascript
<template>
{{ count }} <!-- 直接用!不用 return -->
</template>
- 导入组件就能用
javascript
js
import Child from './Child.vue'
直接在模板用 ,不用注册!
原始写法还要:
javascript
js
export default {
components: { Child }
}
script setup 全都省了。
四、两者功能对比(最关键)
javascript
1. 接收 props
原始 setup:
js
export default {
props: ['title'],
setup(props) {
console.log(props.title)
}
}
script setup:
js
const props = defineProps({
title: String
})
2. 触发事件 emit
javascript
原始 setup:
js
setup(props, { emit }) {
emit('my-event')
}
script setup:
js
const emit = defineEmits(['my-event'])
emit('my-event')
3. 获取 attrs、slots
原始 setup 用 context:
js
setup(props, { attrs, slots })
script setup 用 API:
js
import { useAttrs, useSlots } from 'vue'
const attrs = useAttrs()
const slots = useSlots()
五、最核心区别(背这一段就够)
- setup()
- 手动写,手动 return
- 要写 export default、components
- 代码多,适合老项目、复杂控制
- 不用 return
- 导入组件直接用
- 用 defineProps / defineEmits
- 现在官方推荐、所有人都用这个
六、你能立刻记住的超级口诀
- 原始 setup:手动挡,要 return,麻烦。
- script setup:自动挡,不用 return,简洁好用。
- 功能一模一样,只是写法不一样。
- 现在开发全都用 script setup。
七、我再用最通俗的话总结一遍
javascript
> - setup() 是基础版本,什么都要自己写
> - <script setup> 是懒人舒适版,Vue 帮你把重复的事全干了。
> - 它们底层跑起来是一样的。
> - 你以后写 Vue3,直接用 <script setup> 就对了
八、注册(components)不能写在setup函数里
-
先看注册(components)
Vue 知道:我能用哪些组件,叫什么名字。
-
再解析模板
看到 ,去表里查:有这个名字,认识。
-
最后才执行 setup
去运行子组件自己的逻辑,生成数据、渲染内容。