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 setup
the function. setup
A function is a special function that is the entry point of a component and is called before the component is created. In setup
the 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 count
reactive variable called and created a increment
function called . These variables and functions can be used in the template, or accessed through the component instance.
ref
In the composition API, we use ref
the function to create reactive variables. ref
The function takes an initial value and returns an value
object containing the property. To access or modify the value of a reactive variable, we need to .value
operate 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 name
reactive variable named and defined a updateName
function named to update its value.
computed
In Vue3, we can computed
create computed properties using functions. computed
The function takes a function as an argument and returns a value
reactive 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 firstName
and lastName
and used computed
the function to create a computed property fullName
. fullName
The value of is automatically updated based on changes firstName
in and .lastName
watch
In Vue3, we can use watch
the function to monitor the change of a responsive variable and execute related logic. watch
The 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 count
and use watch
the function to monitor its changes. When count
the 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 onXxx
the 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 onMounted
the function to define the logic executed after the component is mounted. Similarly, we can use onUnmounted
the 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 useTimer
custom Hook called . This Hook provides startTimer
and stopTimer
methods to start and stop the timer. In setup
the 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 setup
functions, 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.