Options API

0 阅读1分钟

Options API:按“选项分类”组织代码(data / computed / methods / watch / mounted 分区)。

1. 代码组织方式

Options:同一个功能的代码会分散在不同区块里(状态在 data,计算在 computed,副作用在 watch,事件在 methods)。

2. 逻辑复用能力

Options:复用通常靠 mixin/高阶组件,容易命名冲突、来源不清晰。

3.TypeScript 体验

Options:this 的类型、上下文推导相对麻烦(尤其复杂组件)。

案例:做一个 计数器,有 count、double,点按钮 +1,并在 count 变化时打印日志。

<template>
  <div>
    <p>count: {{ count }}</p>
    <p>double: {{ double }}</p>
    <button @click="inc">+1</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'CounterOptions',
  data() {
    return {
      count: 0,
    }
  },
  computed: {
    double(): number {
      return this.count * 2
    },
  },
  methods: {
    inc() {
      this.count++
    },
  },
  watch: {
    count(newVal: number, oldVal: number) {
      console.log('count changed:', oldVal, '->', newVal)
    },
  },
  mounted() {
    console.log('mounted, count=', this.count)
  },
})
</script>