Features, usage and best practices of the Vue3 Composition API

Vue3 is a popular JavaScript framework that introduces a new compositional API that provides more flexible and powerful tools when developing large and complex applications. This article will detail the features, usage and best practices of the Vue3 Composition API.

What is a Composition API

Composition API is a new API style in Vue3, which allows developers to organize code according to logical concerns (such as state, computed properties, life cycle, etc.), rather than according to the original option object method. Through the combined API, we can more easily reuse the logic code and improve the readability and maintainability of the code.

setup function

Before using the composition API, we need to understand setupthe function. setupA function is a special function that is the entry point of a component and is called before the component is created. In setupthe function, we can access the props, context and attrs of the component, etc.

import { ref } from 'vue'

export default {
  props: {
    message: String
  },
  setup(props) {
    const count = ref(0)

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

    return {
      count,
      increment
    }
  }
}

In the above code, we defined a countreactive variable called and created a incrementfunction called . These variables and functions can be used in the template, or accessed through the component instance.

ref

In the composition API, we use refthe function to create reactive variables. refThe function takes an initial value and returns an valueobject containing the property. To access or modify the value of a reactive variable, we need to .valueoperate via .

import { ref } from 'vue'

export default {
  setup() {
    const name = ref('John Doe')

    const updateName = () => {
      name.value = 'Jane Smith'
    }

    return {
      name,
      updateName
    }
  }
}

In the above code, we created a namereactive variable named and defined a updateNamefunction named to update its value.

computed

In Vue3, we can computedcreate computed properties using functions. computedThe function takes a function as an argument and returns a valuereactive object with a property. The value of a computed property is automatically updated based on the dependent reactive variable.

import { ref, computed } from 'vue'

export default {
  setup() {
    const firstName = ref('John')
    const lastName = ref('Doe')

    const fullName = computed(() => {
      return `${firstName.value} ${lastName.value}`
    })

    return {
      firstName,
      lastName,
      fullName
    }
  }
}

In the above code, we created two reactive variables firstNameand lastNameand used computedthe function to create a computed property fullName. fullNameThe value of is automatically updated based on changes firstNamein and .lastName

watch

In Vue3, we can use watchthe function to monitor the change of a responsive variable and execute related logic. watchThe function receives two parameters: the reactive variable to monitor and the callback function. When the monitored variable changes, the callback function will be triggered.

import { ref, watch } from 'vue'

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

    watch(count, (newValue, oldValue) => {
      console.log(`Count changed from ${oldValue} to ${newValue}`)
    })

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

    return {
      count,
      increment
    }
  }
}

In the above code, we create a reactive variable countand use watchthe function to monitor its changes. When countthe value of changes, the callback function prints out the old value and the new value.

life cycle hook

In Vue3, lifecycle hooks have changed a bit. Instead, we can use onXxxthe naming convention of to define functions corresponding to lifecycles.

import { onMounted, onUnmounted } from 'vue'

export default {
  setup() {
    onMounted(() => {
      console.log('Component mounted')
    })

    onUnmounted(() => {
      console.log('Component unmounted')
    })
  }
}

In the above code, we use onMountedthe function to define the logic executed after the component is mounted. Similarly, we can use onUnmountedthe function to define the logic to execute when the component is unmounted.

Custom Hook

Custom Hook is a common development pattern, which can help us better organize and reuse logic code. In Vue3, we can use functions to define custom Hooks.

import { ref, onMounted } from 'vue'

function useTimer() {
  const timer = ref(null)

  const startTimer = () => {
    timer.value = setInterval(() => {
      console.log('Timer tick')
    }, 1000)
  }

  const stopTimer = () => {
    clearInterval(timer.value)
    timer.value = null
  }

  onMounted(() => {
    startTimer()
  })

  return {
    startTimer,
    stopTimer
  }
}

export default {
  setup() {
    const { startTimer, stopTimer } = useTimer()

    return {
      startTimer,
      stopTimer
    }
  }
}

In the above code, we defined a useTimercustom Hook called . This Hook provides startTimerand stopTimermethods to start and stop the timer. In setupthe function, we return these methods to the component via destructuring assignment.

Summarize

This article details the features, usage, and best practices of the Vue3 Composition API. We learned concepts like setupfunctions, ref, computed, watch, lifecycle hooks, and custom Hooks.

By using combined API, we can better organize and reuse code, improve development efficiency and code quality.

Guess you like

Origin blog.csdn.net/weixin_43025343/article/details/131813676