Vue3中script&setup

一.script setup

1.1定义

script setup是 Vue3 的一个新[语法糖,相比于普通的语法,简化了组合式API必须return的写法,拥有更好的运行时性能,具体详情参考Vue官方文档。

1.2使用

<script setup> 
const name = '哈哈哈'
</script>

//等同于
<script> 
   setup(){
      const name = '哈哈哈'
      return {
          name
      }
   }
</script>

1.3特点

  1. 声明的内容可以直接在模板中使用
  2. 自动注册组件
  3. 动态组件,应该使用动态的:is来绑定
  4. 必须使用 definePropsdefineEmits API 来声明 props 和 emits
  5. script setup的组件是默认关闭的,需要defineExpose明确要暴露的属性
  6. 通过 useSlotsuseAttrs 两个辅助函数使用slotsattrs
  7. script setup中可以使用顶层 await。结果代码会被编译成 async setup()

二.setup()

setup 方法接受两个参数 setup(props, context)

2.1props 是父组件传给组件的数据

2.2context(上下文)

context中包含了一些常用属性:

  • attrs 表示由上级传向该组件,但并不包含在 props 内的属性
<!-- parent.vue -->
<Child msg="hello world" :name="'child'"></Child>
/* child.vue */
export default {
  props: { name: String },
  setup(props, context) {
    console.log(props) // {name: 'child'}
    console.log(context.attrs) // {msg: 'hello world'}
  },
}
  • emit用于在子组件内触发父组件的方法
<!-- parent.vue -->
<Child @toggle="toggle"></Child>
/* child.vue */
export default {
  setup(_, context) {
    context.emit('toggle')
  },
}
  • slots用来访问被插槽分发的内容,相当于 vm.$slots
<!-- parent.vue -->
<Child>
  <template v-slot:header>
    <div>header</div>
  </template>
  <template v-slot:content>
    <div>content</div>
  </template>
  <template v-slot:footer>
    <div>footer</div>
  </template>
</Child>
/* child.vue */
export default {
  setup(_, context) {
    const { header, content, footer } = context.slots
    return () => h('div', [h('header', header()), h('div', content()), h('footer', footer())])
  },
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明月落乌江

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值