组合式API

组合式API是一系列API的集合,使我们使用函数不用像声明选项的方式书写Vue组件

<script setup>

import { ref, onMounted } from 'vue'

const count = ref(0)

function increment () {
  count.value++
}

onMounted(() => {
  console.log(`count1 is ${count.value}`)
})
</script>

<template>
  <button type="button" @click="increment">count is {{ count }}</button>
</template>
  • setup,关键字,书写的组件模版被编译为了一个内联函数,对代码压缩更好。是因为这种本地变量的名字可以压缩,选项式API依赖 this 上下文访问属性,对象的属性名不能压缩
  • 同一组件,可以使用两种API
    • 选项式API的组件中,通过 setup() 选项来使用组合式API。迫不得已不推荐这种写法
  • 组合式API更适用于大型项目,选项式API适用于中小型项目

results matching ""

    No results matching ""