这是我参与「第五届青训营 」伴学笔记创作活动的第 16 天
Vue中setup语法糖
1.什么是setup语法糖
-
起初 Vue3.0 暴露变量必须
return出来,template中才能使用;
现在只需在script标签中添加setup,组件只需引入,不需要通过return暴露声明的变量、函数以及import引入的内容,也不用写setup函数,也不用写export default ,甚至是自定义指令也可以在我们的template中自动获得。这意味着与普通的
<script>只在组件被首次引入的时候执行一次不同,<script setup>中的代码会在每次组件实例被创建的时候执行
<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来供我们使用
组件通信必须要使用defineProps和defineEmitsAPI来代替props和emits
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/>中可以直接使用父组件传递的props (可省略props.)<script-setup>需要通过props.xx获取父组件传递过来的props
<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
使用 <script setup> 的组件是默认关闭的,即通过模板 ref 或者 $parent 链获取到的组件的公开实例,不会暴露任何在
组件暴露出自己的属性,在父组件中可以拿到。示例:
<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>
4.语法糖其他功能
useSlots 和 useAttrs (少用,由于大部分人是SFC模式开发,在<template/>通过<slot/>标签就可以渲染插槽)
如果需要在script-setup中使用 slots 和 attrs 需要用useSlots 和 useAttrs替代
需要引入:import { useSlots ,useAttrs } form 'vue'
在<template/>中通过 $slots和$attrs 来访问更方便(attrs用来获取父组件中非props的传递到子组件的参数/方法,attrs 用来获取父组件中非props的传递到子组件的参数/方法,attrs用来获取父组件中非props的传递到子组件的参数/方法,slots可以获取父组件中插槽传递的虚拟dom对象,在SFC模式应该用处不大,在JSX /TSX使用比较多)