vue3 setup 配置

128 阅读1分钟

在 Vue 3 中,如果不使用 <script setup> 语法糖,你需要分别使用 setup() 函数和 defineComponent() 函数来编写组件的逻辑部分。

下面是一个简单的示例,展示了如何使用传统的方式编写一个 Vue 3 组件:

Copy Code
<template>
  <div>
    <p>{{ message }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
import { defineComponent, ref } from 'vue';

export default defineComponent({
  data() {
    return {
      count: ref(0)
    };
  },
  methods: {
    increment() {
      this.count++;
    }
  },
  computed: {
    message() {
      return `Count is: ${this.count}`;
    }
  }
});
</script>

在这个例子中,我们使用 defineComponent() 定义了一个组件,并且在 data() 方法中定义了一个响应式的数据 count,使用 methods 对象定义了一个方法 increment(),使用 computed 对象定义了一个计算属性 message

而在 <script setup> 语法糖中,上述代码会被简化为以下形式:

Copy Code
<template>
  <div>
    <p>{{ message }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';

const count = ref(0);

const increment = () => {
  count.value++;
};

const message = computed(() => `Count is: ${count.value}`);
</script>

使用 <script setup> 语法糖,你可以省去了使用 defineComponent() 函数和分别导出组件选项的步骤,使得代码更加简洁和易读。