Home  >  Article  >  Web Front-end  >  How to declare functions in setup in vue

How to declare functions in setup in vue

下次还敢
下次还敢Original
2024-05-09 19:12:19325browse

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

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.computedCreate computed properties

import { defineProps, computed } from 'vue'

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

    // 其他逻辑...

    return {
      // ...其他响应式状态
      incrementCount
    }
  }
}

UseVue .watchCreate 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!

Statement:
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