SoFunction
Updated on 2025-04-07

Examples of declaration and use of VUE3 functions

After understanding how responsive data is used, we will start to understand functions.

In Vue 2, functions are usually declared in methods on the current component instance in methods, and then called in life cycles such as mounted, or triggered in templates through behaviors such as Click. Since this is often needed to obtain component instances within components, arrow functions cannot be used.

export default {
  data: () => {
    return {
      num: 0,
    }
  },
  mounted: function () {
    ()
  },
  methods: {
    // Cannot use `add: () => ++`    add: function () {
      ++
    },
  },
}

In Vue 3, it is much more flexible. You can use ordinary functions, Class classes, arrow functions, anonymous functions, etc. to declare them.It can be used directly by writing it in the setup, or it can be extracted from a separate .js / .ts file and then imported and used.

Functions that need to be automatically executed when component creation need to follow the life cycle of Vue 3, and need to be triggered in the template through @click, @change and other behaviors. Like variables, the function name needs to be returned in the setup.

Here is a simple example to facilitate developers to understand more intuitively:

<template>
  <p>{{ msg }}</p>
  <!-- Click here to execute `return` The method to come out -->
  <button @click="updateMsg">ReviseMSG</button>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue'
export default defineComponent({
  setup() {
    const msg = ref<string>('Hello World!')
    // If this is to be exposed to the template, it must be `return` to use    function updateMsg() {
       = 'Hi World!'
    }
    // This is to be executed when the page is loaded, without the need to go out `return`    const init = () => {
      ('init')
    }
    onMounted(() => {
      init()
    })
    return {
      msg,
      changeMsg,
    }
  },
})
</script>

Summarize

This is the article about the declaration and use of VUE3 functions. For more information about the use of VUE3 function declarations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!