setup语法糖

171 阅读2分钟

setup() 函数是 vue3 中,专门为组件提供的新属性。它为我们使用 vue3的 Composition API 新特性提供了统一的入口, setup 函数会在 beforeCreatecreated 之前执行, vue3也是取消了这两个钩子,统一用setup代替, 该函数相当于一个生命周期函数,vue中过去的datamethodswatch等全部都用对应的新增api写在setup()函数中

 setup()` 接收两个参数 `props` 和 `context`。它里面不能使用 `this`,而是通过 context 对象来代替当前执行上下文绑定的对象,context 对象有四个属性:`attrs`、`slots`、`emit`、`expose

里面通过 refreactive 代替以前的 data 语法,return 出去的内容,可以在模板直接使用,包括变量和方法

 <template>
   <div class="container">
     <h1 @click="say()">{{msg}}</h1>
   </div>
 </template>
 ​
 <script>
 export default {
   setup (props,context) {
     console.log('setup执行了')
     console.log(this)  // undefined
     // 定义数据和函数
     const msg = 'hi vue3'
     const say = () => {
       console.log(msg)
     }
     // Attribute (非响应式对象,等同于 $attrs)
     context.attrs
     // 插槽 (非响应式对象,等同于 $slots)
     context.slots
     // 触发事件 (方法,等同于 $emit)
     context.emit
     // 暴露公共 property (函数)
     context.expose
 ​
     return { msg , say}
   },
   beforeCreate() {
     console.log('beforeCreate执行了')
     console.log(this)  
   }
 }
 </script>

setup语法糖 (script setup语法)

script setup是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。相比于普通的 script 语法更加简洁

要使用这个语法,需要将 setup attribute 添加到 <script> 代码块上:

格式:

 <script setup>
 console.log('hello script setup')
 </script>

顶层的绑定会自动暴露给模板,所以定义的变量,函数和import导入的内容都可以直接在模板中直接使用

 <template>
   <div>
     <h3>根组件</h3>
     <div>点击次数:{{ count }}</div>
     <button @click="add">点击修改</button>
   </div>
 </template>
 ​
 <script setup>
 import { ref } from 'vue'
 ​
 const count = ref(0)
 const add = () => {
   count.value++
 }
 </script>

使用 setup 语法糖时,不用写 export default {},子组件只需要 import 就直接使用,不需要像以前一样在 components 里注册,属性和方法也不用 return。

并且里面不需要用 async 就可以直接使用 await,因为这样默认会把组件的 setup 变为 async setup

用语法糖时,props、attrs、slots、emit、expose 的获取方式也不一样了

3.0~3.2版本变成了通过 import 引入的 API:definePropsdefineEmituseContext(在3.2版本已废弃),useContext 的属性 { emit, attrs, slots, expose }

3.2+版本不需要引入,而直接调用:definePropsdefineEmitsdefineExposeuseSlotsuseAttrs