setup 语法糖

本文介绍了Vue.js中script setup语法糖的使用,包括接收props、声明事件、访问插槽和属性、导出子组件属性以及顶层await的处理。重点讲解了defineProps、defineEmit、useSlots、useAttrs和defineExpose在组件交互中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

**

1.语法

**

<template>
	<Foo></Foo>
</template>
<script setup>
  //导入任意的组件就可以直接在 template 中使用
 import Foo from "./components/Foo"

</script>

2. defineProps 用来接收父组件传来的props defineEmit 用来声明触发的事件

//子组件 msg.vue
<template>
  <div>
    {{ msg }}
    <button @click="onClick">点击按钮</button>
  </div>
</template>
<script setup>
  import { defineProps , defineEmits  } from 'vue'
  let props = defineProps({
 		 msg: String,
	});
	console.log(props); 
  
  
	const emit = defineEmits(['click'])
  const onClick = () => {
  	emit('click');
  }
</script>  
//父组件 app.vue
<template>
  <msg msg="天气很好" @click="onClick"></msg>
</template>

<script setup>
import msg from "./components/msg.vue"
  const onClick = () =>{
  	console.log("接收子组件的点击事件");
  };
</script>

3. useSlots 和useAttrs

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

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

4. defineExpose 如果在父组件中通过ref="xxx"的方式来获取子组件实例,子组件使用了script setup 语法糖,则子组件的数据需要用defineExpose 的方式导出,否则不会暴露属性

//父组件

<template>
  <Daughter ref="daughter" />
</template>

<script lang="ts" setup>
import { ref } from "vue";
import Daughter from "./Daughter.vue";

const daughter = ref(null)
console.log('~daughter',daughter)
</script>


//子组件

<template>
  <div>哈哈哈{{ msg }}</div>
</template>

<script lang="ts" setup>
import { ref ,defineExpose} from "vue";
const msg = ref('你好')
defineExpose({
    msg
})
</script>


5. 顶层 await 结果代码会被编译成async setup()

<script setup>
	const post = await fetch(`/api/post/1`).then(r => r.json())
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值