script setup lang="ts">和export default { setup() {区别是什么

发布时间 2023-07-27 14:09:49作者: yjxQWQ

script setup lang="ts">和export default { setup() {区别是什么

setup 是 Vue 3 新增的语法糖,可以让我们使用更简洁的代码来编写组件。它在编译时会将代码转换为使用 setup 函数的形式,省略了传统 Vue 组件中的 template、data、methods 等属性的定义。

模板

<template>
  <div class="emoji-picker"></div>
</template>

<script setup lang="ts">
import { watch } from "vue";
interface Emoji {
  id: number;
  symbol: string;
}
const emit = defineEmits(["EmojiPickerclick"]);
const props = defineProps({
  value: {
    type: String,
    default: "",
  },
});
</script>
<style scoped></style>

另一种写法是

<template>
  <div>
    <p>Counter: {{ counter }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
export default {
  setup() {
    // 在setup函数内部可以使用Vue 3的Composition API函数
    // 例如,使用ref来创建一个响应式的变量
    const counter = ref(0);

    // 编写组件的逻辑,例如增加计数器的功能
    function increment() {
      counter.value++;
    }

    // 返回希望在模板中使用的数据和方法
    // 这里返回的对象可以包含任何你希望在模板中使用的响应式数据或方法
    return {
      counter,
      increment,
    };
  },
};
</script>