Home > Web Front-end > Vue.js > body text

How to declare functions in setup in vue

下次还敢
Release: 2024-05-09 19:12:19
Original
564 people have browsed it

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

How to declare functions in setup in vue

Declaring functions in setup in Vue

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>
Copy after login

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>
Copy after login

UseVue.computedCreate computed properties

<code class="js">import { defineProps, computed } from 'vue'

export default {
  props: defineProps(['count']),
  setup() {
    const incrementCount = computed(() => {
      // ...
    })

    // 其他逻辑...

    return {
      // ...其他响应式状态
      incrementCount
    }
  }
}</code>
Copy after login

UseVue .watchCreate 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>
Copy after login

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!

Related labels:
vue
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!