vue3 setup语法糖 详细使用说明

3 篇文章 0 订阅
1 篇文章 0 订阅

在Vue3 中 setup 有两种表现方式:

一种是 我们常用的:
<script>
 export default {
 	name: 'home',
     setup() {
       return {};
     },
 };
</script>
还有一种是 setup 语法糖:(给组件起名字,就需要 按照原本的方式 导出了)
 <script> export default { name: 'home', } </script>
 <script setup>
 
 </script>
那我就来介绍一下 setup 语法糖的用法:
  1. 挂在组件
 <template>
 		<Index /> 
 </template>
 <script setup>
 	// 不需要挂载注册
 	import Index from './index.vue';
 </script>
  1. 使用 refs 的一系列操作
 // 父组件 Father.vue
 <template>
 		<Index ref="IndexRefs" /> 
 </template>
 <script setup>
 	import Index from './index.vue';
 	import { onMounted , ref } from 'vue';
 	
 	const IndexRefs = ref(null)
 	
 	onMounted (()=>{
 			IndexRefs.value.num +1			// 1
 			IndexRefs.value.click()			// 2
 	})
 </script>

 // 子组件 Index.vue
 <template>
 		num:{{ num }}
 </template>
 <script setup>
 	import { ref } from 'vue';
 	
 	const num = ref(0)
 	const click = () =>{
     	num .value +2
     }
 	
 	// 父级想操作的数据 或者 方法导出去
 	defineExpose({
 	    num
 	    click 
 	 });
 </script>
  1. 组件之间 相互 传参
 // 父传子
 // 父组件 Father.vue
 <template>
 		<Index :num="num" /> 
 </template>
 <script setup>
 	import Index from './index.vue';
 	import { ref } from 'vue';
 	const num = ref(10)
 	
 </script>

 // 子组件 Index.vue
 <template>
 		{{ num }}
 </template>
 <script setup>
 	// 接收值
 	const { num } = defineProps({
 	    num : Number,
 	});	
 	console.log('num' , num) 
 </script>

 // 子传父
 // 父组件 Father.vue
 <template>
 		<Index @porpsClick="btn"  /> 
 </template>
 <script setup>
 	import Index from './index.vue';
 	const btn = (_porps) => {
 		console.log('_porps' , _porps)		// 123
 	}
 	
 </script>

 // 子组件 Index.vue
 <template>
 		<button @click="btn">点我传参</button>
 </template>
 <script setup>
 	const emit = defineEmits(['porpsClick']);
 	const btn = () =>{
 		emit( 'porpsClick' , 123 )
 	}
 </script>
  1. useSlots 和 useAttrs 使用
	<script setup>
		import { useAttrs, useSlots } from 'vue';

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

此文章是为了记录学习,
有什么没提到的可以交流,互相学习

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值