Skip to content

Vue 3 组合式 API

setup 语法

vue
<script setup>
import { ref, computed } from 'vue'

const count = ref(0)
const double = computed(() => count.value * 2)

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

<template>
  <button @click="increment">{{ count }} x2 = {{ double }}</button>
</template>

生命周期

javascript
import { onMounted, onUnmounted } from 'vue'

onMounted(() => console.log('已挂载'))
onUnmounted(() => console.log('已卸载'))

组合式函数(Composables)

javascript
// useCounter.js
export function useCounter(initial = 0) {
  const count = ref(initial)
  const increment = () => count.value++
  return { count, increment }
}

基于 VitePress 构建