Home >Web Front-end >Vue.js >How to declare functions in setup in vue
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
<code class="js">import { defineProps } from 'vue' export default { props: defineProps(['count']), setup() { function incrementCount() { // ... } // 其他逻辑... return { // ...其他响应式状态 incrementCount } } }</code>
Use Vue.reactive
Create mutable reactive objects
<code class="js">import { defineProps, reactive } from 'vue' export default { props: defineProps(['count']), setup() { const state = reactive({ count: 0, increment: function() { // ... } }) // 其他逻辑... return { // ...其他响应式状态 ...state } } }</code>
UseVue.computed
Create computed properties
<code class="js">import { defineProps, computed } from 'vue' export default { props: defineProps(['count']), setup() { const incrementCount = computed(() => { // ... }) // 其他逻辑... return { // ...其他响应式状态 incrementCount } } }</code>
UseVue .watch
Create a listener
<code class="js">import { defineProps, watch } from 'vue' export default { props: defineProps(['count']), setup() { const incrementCount = watch('count', (newValue, oldValue) => { // ... }) // 其他逻辑... return { // ...其他响应式状态 incrementCount } } }</code>
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!