在 Vue 3 <script setup> 中使用 JavaScript 类

是的,在 Vue 3 的 <script setup> 语法中完全可以定义和使用 JavaScript 类(Class)。以下是详细说明:

基本用法

vue

<script setup>
// 直接在 <script setup> 中定义类
class User {
  constructor(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }

  get fullName() {
    return `${this.firstName} ${this.lastName}`
  }
}

// 使用类创建实例
const user = new User('张', '三')
</script>

<template>
  <div>{{ user.fullName }}</div>
</template>

响应式处理

如果需要使类实例具有响应性,可以使用 reactive 或 ref

vue

<script setup>
import { reactive } from 'vue'

class Counter {
  constructor() {
    this.count = 0
  }

  increment() {
    this.count++
  }
}

// 使类实例具有响应性
const counter = reactive(new Counter())
</script>

<template>
  <button @click="counter.increment()">{{ counter.count }}</button>
</template>

作为组件属性暴露

如果需要将类方法暴露给模板使用:

vue

<script setup>
class Timer {
  constructor() {
    this.seconds = 0
    this.timer = null
  }

  start() {
    this.timer = setInterval(() => this.seconds++, 1000)
  }

  stop() {
    clearInterval(this.timer)
  }
}

const timer = new Timer()
// 如果需要响应性
const reactiveTimer = reactive(timer)

// 暴露给模板
defineExpose({
  timer,
  startTimer: timer.start,
  stopTimer: timer.stop
})
</script>

作为组件 props 传递

也可以将类实例作为 props 传递:

vue

<!-- ParentComponent.vue -->
<script setup>
import ChildComponent from './ChildComponent.vue'
import { reactive } from 'vue'

class User {
  // ...类定义
}

const user = reactive(new User('李', '四'))
</script>

<template>
  <ChildComponent :user="user" />
</template>

<!-- ChildComponent.vue -->
<script setup>
defineProps({
  user: {
    type: Object,
    required: true
  }
})
</script>

注意事项

  1. 响应性问题:普通类实例默认不是响应式的,需要使用 reactive() 或 ref() 包装

  2. 方法绑定:类方法中的 this 需要正确绑定,建议使用箭头函数或在构造函数中绑定

  3. 性能考虑:对于简单的数据逻辑,组合式函数可能比类更轻量

  4. TypeScript:如果使用 TypeScript,可以更好地支持类类型检查

最佳实践

  • 对于复杂业务逻辑,使用类封装是个好选择

  • 对于UI相关状态,推荐使用组合式API的响应式系统

  • 考虑将类定义放在单独的文件中,保持组件简洁

在 <script setup> 中使用类是完全可行的,这为组织复杂逻辑提供了更多选择。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐