Skip to content

Composition API

为什么需要 Composition API?

Composition API 带来的不只是语法的变化,更是 组织组件逻辑的新方式

简单回顾 Options API

  • 简单清晰、适合小组件。

痛点:当组件逐渐复杂时,会发现同一块逻辑会被分散到多个块之中,不易维护。

html
<script>
  export default {
    data() {
      return {
        count: 0,
      }
    },
    methods: {
      increment() {
        this.count++
      },
    },
    computed: {
      double() {
        return this.count * 2
      },
    },
  }
</script>

Composition API 的优势

  • 相关逻辑更集中。
  • 更容易抽离成函数(组合式函数)。
  • 更友好的类型推导。
html
<script setup>
  import { ref, computed } from 'vue'

  const count = ref(0)
  const increment = () => {
    count.value++
  }
  const double = computed(() => count.value * 2)
</script>

引入 setup

<script setup> 这很 “Hooks 写法”!

html
<script>
  import { ref } from 'vue'

  export default {
    setup() {
      const count = ref(0)

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

      return {
        count,
        increment,
      }
    },
  }
</script>
html
<script setup>
  import { ref } from 'vue'

  const count = ref(0)

  const increment = () => {
    count.value++
  }
</script>

基于 MIT 许可发布