在 Vue 3 中,<script setup>
是一个实验性的 API,用于使用 Composition API 编写组件。它允许你在一个更简洁、更有组织的方式中编写组件。这种语法能够让你直接在 <script setup>
标签内使用 ref
、computed
、watch
等 Composition API 的函数,而无需在 setup
函数内部使用它们。
基本用法
普通的 Composition API 写法:
<template>
<div>{{ count }}</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
return {
count,
};
},
};
</script>
使用 <script setup>
的写法:
<template>
<div>{{ count }}</div>
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
</script>
如你所见,<script setup>
语法更加简洁。
导出引用
使用 defineProps
、defineEmits
和 withDefaults
,你可以定义组件的 props
和 emits
:
<script setup>
import { defineProps, defineEmits, withDefaults } from 'vue';
const props = withDefaults(defineProps(), {
color: 'blue',
});
const emit = defineEmits(['update']);
</script>
使用其他 Composition API
<script setup>
允许你直接使用如 watch
、computed
等其他 Composition API
<script setup>
import { ref, computed } from 'vue';
const count = ref(0);
const double = computed(() => count.value * 2);
</script>
使用 <script setup>
和普通 <script>
的混合
你也可以在同一组件中同时使用 <script setup>
和普通的 <script>
,但 <script setup>
必须出现在普通的 <script>
之前:
<script setup>
import { ref } from 'vue';
const count = ref(0);
</script>
<script>
export default {
methods: {
increment() {
this.count++;
},
},
};
</script>
总体来说,<script setup>
提供了一种更简洁、更高效的方式来使用 Composition API,而这正是它被引入的主要原因。