Vue3.2中的setup语法糖 | 青训营笔记 第 10 天

135 阅读1分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 10 天

Vue3.2中的setup语法糖

1.什么是setup语法糖

  • 起初 Vue3.0 暴露变量必须 return 出来,template中才能使用;
    现在只需在script标签中添加setup,组件只需引入不用注册,属性和方法也不用返回,也不用写setup函数,也不用写export default ,甚至是自定义指令也可以在我们的template中自动获得。
<template>   
  <my-component :num="num" @click="addNum" /> 
</template>

<script setup>   
import { ref } from 'vue';   
import MyComponent from './MyComponent .vue';

// 像在平常的setup中一样的写,但是不需要返回任何变量   
const num= ref(0)       
//在此处定义的 num 可以直接使用   
const addNum= () => {   
  //函数也可以直接引用,不用在return中返回     
  num.value++   
} 
</script>
//必须使用驼峰命名

2.使用setup组件自动注册

在 script setup 中,引入的组件可以直接使用,无需再通过components进行注册,并且无法指定当前组件的名字,它会自动以文件名为主,也就是不用再写name属性了。需要注意名字要一致,示例:

<template>     
  <zi-hello></zi-hello> 
</template>

<script setup>   
  import ziHello from './ziHello' 
</script>

3.使用setup后新增API

因为没有了setup函数,那么props,emit怎么获取呢

Setup script语法糖提供了新的API来供我们使用

3.1 defineProps

用来接收父组件传来的 props。示例:

<template>   
  <div class="die">     
  	<h3>我是父组件</h3>     
  	<zi-hello :name="name"></zi-hello>   
  	</div>
</template>

<script setup>   
import ziHello from './ziHello'      
import {ref} from 'vue'   
let name = ref(' zhi ') 
</script>
<template>   
  <div>     
  我是子组件{{name}} // zhi
</div> </template>

<script setup>   
import {defineProps} from 'vue'

defineProps({    
  name:{      
    type:String,      
    default:'我是默认值'    
  }  
}) 
</script>

3.2 defineEmits

子组件向父组件事件传递。示例:

<template>   
  <div>     
  我是子组件{{name}}     
	<button @click="ziupdata">按钮</button>   
  </div> 
</template>

<script setup>   
import {defineEmits} from 'vue'
//自定义函数,父组件可以触发   
const em=defineEmits(['updata'])   
const ziupdata=() => {     
  em("updata",'我是子组件的值')   
}
</script>
<template>   
  <div class="die">     
  <h3>我是父组件</h3>     
  <zi-hello @updata="updata"></zi-hello>   
  </div> 
</template>

<script setup>   
import ziHello from './ziHello'      
const updata = (data) => {
  console.log(data); //我是子组件的值   
} 
</script>

3.3 defineExpose

组件暴露出自己的属性,在父组件中可以拿到。示例:

<template>   
  <div>     
  我是子组件   
  </div> 
</template>

<script setup>   
import {defineExpose,reactive,ref} from 'vue'   
  let ziage=ref(18)   
  let ziname=reactive({
  name:'zhi'   
})   //暴露出去的变量   
defineExpose({     
  ziage,     
  ziname   
}) 
</script>
<template>   
  <div class="die">     
  	<h3 @click="isclick">我是父组件</h3>     
  <zi-hello ref="zihello"></zi-hello>   
	</div> 
</template>

<script setup>   
import ziHello from './ziHello'   
import {ref} from 'vue'   
const zihello = ref()
const isclick = () => {
  console.log('接收ref暴漏出来的值',zihello.value.ziage) 
  console.log('接收reactive暴漏出来的值',zihello.value.ziname.name)
}
</script>