簡介
<script setup>
語法糖並不是新增的功能模塊,它只是簡化了以往的組合API(compositionApi)
的必須返回(return)
的寫法,並且有更好的運行時性能。
在 setup 函數中:所有 ES 模塊導出都被認為是暴露給上下文的值,並包含在 setup()
返回對象中。相對於之前的寫法,使用后,語法也變得更簡單。
你不必擔心setup語法糖
的學習成本,他是組合式API的簡化,並沒有新增的知識點。你只需要了解一些用法和細微的不同之處,甚至比之前寫setup()
還要順手!
使用方式極其簡單,僅需要在 script 標簽加上 setup 關鍵字即可。示例:
<script setup>
</script>
注:因為setup語法糖是vue3.2正式確定下來的議案,所以vue3.2的版本是真正適合setup語法糖的版本。
1. 屬性和方法無需返回,直接使用
以前使用響應式數據是:
<template>
{{msg}}
</template>
<script>
import { ref } from 'vue'
export default {
setup () {
const msg = ref('hello vue3');
return {
msg
}
}
}
</script>
現在使用 setup 語法糖,不需要return返回
和 setup函數
,只需要全部定義在<script setup>
內即可:
<template>
{{msg}}
</template>
<script setup>
import { ref } from 'vue'
const msg = ref('hello vue3');
</script>
reactive
, computed
, 也一樣可以使用:
<template>
<div>{{msg}}</div>
<div>{{obj.a}}</div>
<div>{{sum}}</div>
</template>
<script setup>
import { ref, reactive, computed } from 'vue'
const msg = ref('hello vue3');
const obj = reactive({
a: 1,
b: 2
})
const sum = computed(() => {
return obj.a + 3;
});
</script>
2. 組件自動注冊
在 script setup 中,引入的組件可以直接使用,無需再通過components進行注冊,並且無法指定當前組件的名字,它會自動以文件名為主,也就是不用再寫name屬性了。示例:
<template>
<Child />
</template>
<script setup>
import Child from '@/components/Child.vue'
</script>
3. 組件數據傳遞(props和emits)
props
和 emits
在語法糖中使用 defineEmits
和 defineProps
方法來使用:
子組件 Child.vue:
<template>
<div @click="toEmits">Child Components</div>
</template>
<script setup>
// defineEmits,defineProps無需導入,直接使用
const emits = defineEmits(['getChild']);
const props = defineProps({
title: {
type: String,
defaule: 'defaule title'
}
});
const toEmits = () => {
emits('getChild', 'child value') // 向父組件傳遞數據
}
// 獲取父組件傳遞過來的數據
console.log(props.title); // parent value
</script>
父組件 Home.vue:
<template>
<Child @getChild="getChild" :title="msg" />
</template>
<script setup>
import { ref } from 'vue'
import Child from '@/components/Child.vue'
const msg = ref('parent value')
const getChild = (e) => {
// 接收父組件傳遞過來的數據
console.log(e); // child value
}
</script>
4. 獲取 slots 和 attrs
可以通過useContext從上下文中獲取 slots 和 attrs。不過提案在正式通過后,廢除了這個語法,被拆分成了useAttrs和useSlots。示例:
// 舊
<script setup>
import { useContext } from 'vue'
const { slots, attrs } = useContext()
</script>
// 新
<script setup>
import { useAttrs, useSlots } from 'vue'
const slots = useSlots();
const attrs = useAttrs();
console.log(attrs.dataId); // 查看父組件傳來的自定義屬性
</script>
5. 對外暴露屬性(defineExpose)
<script setup>
的組件默認不會對外部暴露任何內部聲明的屬性。
如果有部分屬性要暴露出去,可以使用 defineExpose
子組件 Child.vue:
<template>
{{msg}}
</template>
<script setup>
import { ref } from 'vue'
let msg = ref("Child Components");
let num = ref(123);
// defineExpose無需導入,直接使用
defineExpose({
msg,
num
});
</script>
父組件 Home.vue:
<template>
<Child ref="child" />
</template>
<script setup>
import { ref, onMounted } from 'vue'
import Child from '@/components/Child.vue'
let child = ref(null);
onMounted(() => {
console.log(child.value.msg); // Child Components
console.log(child.value.num); // 123
})
</script>