大家可能发现了,虽然我们可以进行关注点分离代码,但是setup函数里面的代码依旧看起来很多,那么有没有什么方法可以让setup变的更加简短一些呢?下面我就介绍一下vue3最近发布的script setup语法糖,可真是用起来特别甜。
1、setup基本用法:
使用起来特别简单,只需要在script标签上加上setup关键字即可。
<script setup></script>
2、组件自动注册
在script setup中,引入的组件,无需在components注册。
<script setup>
import HelloWorld from './components/HelloWorld.vue'
</script>
<template>
<HelloWorld msg="Hello Vue 3 + Vite" />
</template>
3、组件核心API的使用
(1)使用defineProps
通过 defineProps 指定当前props类型,获得上下文的props对象。
<script setup>
import { ref } from 'vue'
const props = defineProps({
msg: String
})
const count = ref(0)
</script>
(2)使用emits
父组件:
<script setup>
import HelloWorld from './components/HelloWorld.vue'
const handle = (val) => {
console.log(val); //天下
}
</script>
<template>
<HelloWorld
msg="Hello Vue 3 + Vite"
@handle="handle"
/>
</template>
子组件:
<script setup>
import {
defineEmits
} from 'vue'
const emits = defineEmits("handle");
const handleClick = ()=> {
emits("handle","天下")
}
</script>
<template>
<button type="button" @click="handleClick">点击</button>
</template>
(3)获取slots和attrs
通过useAttrs、useSlots分别获取slots和attrs。
<script setup>
import { defineProps,useAttrs,useSlots } from 'vue'
const attrs = useAttrs();
const slots = useSlots();
</script>
(4)属性和方法无需返回,直接使用
之前,setup函数中的变量和函数都要return,才能在模板中使用,现在在script setup中定义无需return,直接可以使用,有没有感觉到意外的惊喜?
<script setup>
import { ref } from 'vue'
const count = ref(0)
const handleClick = ()=> count.value++
</script>
<template>
<button type="button" @click="handleClick">count is: {{ count }}</button>
</template>
大家有没有觉得简单多了。