setup 语法糖的使用

Vue 单文件组件 <script setup> API
SFC 组件组合式 API 语法糖 (<script setup>)

1. 导入组件

<script setup>内导入的组件,可以直接在模版中使用。

<template>
  <my-com />
</template>
<script setup>
// 导入的组件可以直接在 template 中使用
import MyCom from '@components/MyCom'
</script>

2. 定义 props

<template>
  <div>我是子组件 My-Com : {{ msg }}</div>
</template>

<script setup>
defineProps({
  msg: String,
})
</script>

3. 定义事件

子组件:

<template>
  <div>我是子组件 My-Com : {{ msg }}</div>
  <button @click="emit('update-msg', 'hi')">update</button>
  <!--或者-->
  <button @click="deleteMsg">delete</button>
</template>

<script setup>
defineProps({
  msg: String,
})
//  定义发出的事件
const emit = defineEmits(['update-msg', 'delete-msg'])
const deleteMsg = () => {
  emit('delete-msg')
}
</script>

父组件:

<template>
  <!--父组件接收事件的方式也没区别,就是用 @ 接收-->
  <my-com :msg="msg" @update-msg="updateFun" @delete-msg="deleteFun"></my-com>
</template>

<script setup>
import {  ref } from 'vue'
import MyCom from '@components/MyCom.vue'

// 定义组件状态 和 方法 都和之前没有区别,只是不用 return 出去了
const msg = ref('Hello')

const updateFun = param => {
  console.log('update', param)
}
const deleteFun = () => {
  msg.value = ''
}
</script>

4. 变量和方法

由第 3 点事件的例子也可以看到,声明在<script setup>顶层的状态、函数,以及 import 引入的变量和方法,都能在模板中直接使用,不用再通过 return 暴露出去。

<script setup>
import { capitalize } from './helpers'
</script>

<template>
  <div>{{ capitalize('hello') }}</div>
</template>

5. 对组件外暴露属性

<script setup> 的组件默认不会对外部暴露任何内部声明的属性。如果有部分属性要暴露出去,可以使用 defineExpose 编译器宏:

<script setup>
import { ref } from 'vue'
const a = 1
const b = ref(2)

defineExpose({
  a,
  b
})
</script>

父组件通过模板 ref 获取到子组件的实例,以此访问 MyCom 暴露出去的属性:

<script setup>
import { onMounted, ref } from 'vue'
import MyCom from '@components/MyCom.vue'

const myComRef = ref(null)
onMounted(() => {
  console.log(myComRef, myComRef.value.a)
})
</script>

<template>
  <my-com :msg="msg" ref="myComRef" />
</template>

6. useSlots 和 useAttrs

等价于组合式 API setup(props, context)context.slotscontext.attrs。也可以解构获取:setup(props, {slots,attrs})。它们的使用场景还是很稀少的。

<script setup>
  import { useSlots, useAttrs } from 'vue'

  const slots = useSlots()
  const attrs = useAttrs()
</script>

7. Top-level await/顶层 await

<script setup> 内可以使用Top-level await,结果代码会被编译成 async setup()。

<script setup>
  const post = await fetch(`@api/post/1`).then((r) => r.json())
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容