Vue 3 `<script setup>`:介绍与使用

111 阅读1分钟

Vue 3 引入了一种新的组件脚本语法,即 <script setup>,它是 Composition API 的语法糖,允许你以更简洁的方式编写组件。

介绍

<script setup> 是 Vue 3.2 之后的一个新特性,它允许你在单文件组件中使用更简洁、更直观的方式来使用 Composition API。它可以减少样板代码,并使组件逻辑更加清晰。

使用

基本用法

<script setup> 中,你可以直接使用 import 语句导入所需的依赖,而不需要包装在 setup 函数中。

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

const message = ref('Hello, Vue 3!');
</script>

<template>
  <div>{{ message }}</div>
</template>

使用 Props

你可以使用 defineProps 函数来定义组件的 props:

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

const props = defineProps({
  message: String,
});
</script>

<template>
  <div>{{ message }}</div>
</template>

使用 Components

你可以直接导入和使用其他组件:

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

<template>
  <MyComponent />
</template>

使用 Computed 和 Watch

你可以直接使用 computedwatch 函数,而不需要将它们包装在 setup 函数中:

<script setup>
import { ref, computed, watch } from 'vue';

const count = ref(0);
const doubledCount = computed(() => count.value * 2);

watch(count, (newVal, oldVal) => {
  console.log(`Count changed from ${oldVal} to ${newVal}`);
});
</script>

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Doubled Count: {{ doubledCount }}</p>
    <button @click="count++">Increment</button>
  </div>
</template>

通过这些示例,你可以看到 <script setup> 提供了一种更简洁、更直观的方式来使用 Composition API。希望这能帮到你!