基础语法
将setup属性添加到script标签上
<script setup>
console.log('hello script setup')
</script>
脱离了模板的vue3 类似于react的函数式编程 (以后的react hooks和vue3可以无缝切换)
定义组件名 name
script-setup 无法指定当前组件的名字,所以使用的时候以文件名为主
使用组件 component
<script setup>
import MyComponent from './MyComponent.vue'
</script>
<template>
<MyComponent />
</template>
引入组件后 可以在template中直接使用
使用自定义指令 directive
<script setup>
const vMyDirective = {
beforeMount: (el) => {
// 在元素上做些操作
}
}
</script>
<template>
<h1 v-my-directive>This is a Heading</h1>
</template>
<script setup>
// 导入的指令同样能够工作,并且能够通过重命名来使其符合命名规范
import { myDirective as vMyDirective } from './MyDirective.js'
</script>
全局注册的自定义指令将可以正常使用,本地注册的指令可以直接在模板中使用
限制:必须以 vNameOfDirective 的形式来命名本地自定义指令,如上
使用Props
通过defineProps指定当前props类型的同时,获得上下文的props对象
在script中需要props[key]引用,而template中可直接调用key
<script setup>
import { defineProps } from 'vue'
// expects props options
const props = defineProps({
foo: String,
})
</script>
使用emits
通过defineEmits指定当前组件含有的触发事件
事件通过 defineEmits 返回的上下文 emit 进行触发
<script setup>
import { defineEmits } from 'vue'
// expects emits options
const emits = defineEmits(['update', 'delete'])
</script>
使用slots、attrs
<script setup>
import { useSlots, useAttrs } from 'vue'
const slots = useSlots()
const attrs = useAttrs()
</script>