There are four ways to declare functions in setup: declare the function directly, use Vue.reactive to create a variable responsive object, use Vue.computed to create a calculated property, use Vue.watch to create a listener
In Vue 3.0, the setup
function provides a way to declare reactive state, computed properties and methods New way. Here's how to declare a function in setup
:
Declare the function directly
import { defineProps } from 'vue' export default { props: defineProps(['count']), setup() { function incrementCount() { // ... } // 其他逻辑... return { // ...其他响应式状态 incrementCount } } }
Use Vue.reactive
Create mutable reactive objects
import { defineProps, reactive } from 'vue' export default { props: defineProps(['count']), setup() { const state = reactive({ count: 0, increment: function() { // ... } }) // 其他逻辑... return { // ...其他响应式状态 ...state } } }
UseVue.computed
Create computed properties
import { defineProps, computed } from 'vue' export default { props: defineProps(['count']), setup() { const incrementCount = computed(() => { // ... }) // 其他逻辑... return { // ...其他响应式状态 incrementCount } } }
UseVue .watch
Create a listener
import { defineProps, watch } from 'vue' export default { props: defineProps(['count']), setup() { const incrementCount = watch('count', (newValue, oldValue) => { // ... }) // 其他逻辑... return { // ...其他响应式状态 incrementCount } } }
Through these methods, you can declare functions in a reactive manner in the setup
function of Vue 3.0.
The above is the detailed content of How to declare functions in setup in vue. For more information, please follow other related articles on the PHP Chinese website!