In this tutorial, we will focus on the setup()
function in Vue.js, a crucial part of the Composition API. The setup()
function is the entry point for using the Composition API, which allows you to organize your component's logic in a more intuitive and flexible way.
By the end of this tutorial, you will learn how to use and compose the logic of your Vue components using the setup()
function.
Prerequisites: Basic understanding of JavaScript and Vue.js.
The setup()
function is where you define all the reactive data, computed properties, functions, and lifecycle hooks of your component when using the Composition API.
The setup()
function is a new component option in Vue.js 3. It serves as the entry point for using the Composition API within your Vue components.
Here's an example of a very basic setup()
function:
export default {
setup() {
// component logic here
}
}
To create reactive data, you use the reactive()
or ref()
functions within setup()
.
import { reactive } from 'vue'
export default {
setup() {
const state = reactive({
count: 0,
})
return { state }
}
}
In this example, state
is a reactive object with a count
property.
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
const increment = () => {
count.value++
}
return { count, increment }
}
}
In this example, count
is a reactive reference to the number 0, and increment
is a method that increases count
by one. These are then returned from setup()
so they can be used in the template.
import { ref, computed } from 'vue'
export default {
setup() {
const count = ref(0)
const double = computed(() => count.value * 2)
return { count, double }
}
}
In this example, double
is a computed property that's always twice the value of count
.
We've covered how to use the setup()
function to create a component's reactive data and methods, and how to return these to make them available in the template. Your next step could be to learn about lifecycle hooks in the Composition API, or how to extract and reuse logic between components.
setup()
.setup()
function instead.Here's a solution for exercise 1:
import { ref } from 'vue'
export default {
setup() {
const name = ref('Vue')
const greet = () => {
console.log(`Hello, ${name.value}!`)
}
return { name, greet }
}
}
In this example, name
is a reactive reference to the string 'Vue', and greet
is a method that logs a greeting to the console. These are then returned from setup()
so they can be used in the template.