Options API和Composition API

vue 收藏
0 33
选项 API

通过选项 API,我们使用选项对象(例如 、 和 )定义组件datamethods逻辑mounted由选项定义的属性在内部函数上公开this,该函数指向组件实例:

<script>
export default {
  // Properties returned from data() become reactive state
  // and will be exposed on `this`.
  data() {
    return {
      count: 0
    }
  },

  // Methods are functions that mutate state and trigger updates.
  // They can be bound as event handlers in templates.
  methods: {
    increment() {
      this.count++
    }
  },

  // Lifecycle hooks are called at different stages
  // of a component's lifecycle.
  // This function will be called when the component is mounted.
  mounted() {
    console.log(`The initial count is ${this.count}.`)
  }
}
</script>

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

通过 Composition API,我们使用导入的 API 函数定义组件的逻辑。在 SFC 中,组合 API 通常与setup属性是一个提示,使 Vue 执行编译时转换,使我们能够使用更少样板的 Composition API。例如,声明的导入和顶级变量/函数可以直接在模板中使用。

这是相同的组件,具有完全相同的模板,但使用 Composition API 

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

// reactive state
const count = ref(0)

// functions that mutate state and trigger updates
function increment() {
  count.value++
}

// lifecycle hooks
onMounted(() => {
  console.log(`The initial count is ${count.value}.`)
})
</script>

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


    暂时没有人评论