一.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特点
- 声明的内容可以直接在模板中使用
- 自动注册组件
- 动态组件,应该使用动态的
:is
来绑定 - 必须使用
defineProps
和 defineEmits
API 来声明 props 和 emits script setup
的组件是默认关闭的,需要defineExpose
明确要暴露的属性- 通过
useSlots
和 useAttrs
两个辅助函数使用slots
和 attrs
script setup
中可以使用顶层 await。结果代码会被编译成 async setup()
二.setup()
setup
方法接受两个参数 setup(props, context)
2.1props
是父组件传给组件的数据
2.2context
(上下文)
context中包含了一些常用属性:
attrs
表示由上级传向该组件,但并不包含在 props
内的属性
<Child msg="hello world" :name="'child'"></Child>
export default {
props: { name: String },
setup(props, context) {
console.log(props)
console.log(context.attrs)
},
}
<Child @toggle="toggle"></Child>
export default {
setup(_, context) {
context.emit('toggle')
},
}
slots
用来访问被插槽分发的内容,相当于 vm.$slots
<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>
export default {
setup(_, context) {
const { header, content, footer } = context.slots
return () => h('div', [h('header', header()), h('div', content()), h('footer', footer())])
},
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)