Options API 和 Composition API

发布时间 2024-01-02 14:25:29作者: 树山君

1、vue2 使用 Options API (选项API),逻辑分散在 data, methods, props, filters, mounted, created 中

<template>
  <button @click="increment">count is: {{ count }}</button>
</template>
<script
export default {
  data(){
    return {
      count: 0
    }
  },
  methods: {
    increment(){
      this.count++
    }
  },
  mounted(){
    console.log('initial count: ', this.count)
  }
}
</script>

2、vue3 使用 Composition API (组合式API),使用导入的API函数定义组件的逻辑

<template>
  <button @click="increment">Count is: {{ count }}</button>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  const count = ref(0)
  function increment(){
    count.value++
  }
  onMounted(()=>{
    console.log(`initial count is: ${count.value}`)
  })
</script>