Declaration and use of VUE3 functions

After understanding how reactive data is used, the next step is to understand functions.

In Vue 2, functions are usually declared in methods as methods on the current component instance, and then called in life cycles such as mounted, or triggered by behaviors such as Click in the template, because components often need to use this to obtain component instances , so arrow functions cannot be used.

export default {
    
    
  data: () => {
    
    
    return {
    
    
      num: 0,
    }
  },
  mounted: function () {
    
    
    this.add()
  },
  methods: {
    
    
    // 不可以使用 `add: () => this.num++`
    add: function () {
    
    
      this.num++
    },
  },
}

In Vue 3, it is much more flexible. You can use ordinary functions, Class classes, arrow functions, anonymous functions, etc. to declare. You can write them in the setup and use them directly, or you can extract them in independent .js / .ts files Then import and use.

Functions that need to be automatically executed when the component is created must follow the life cycle of Vue 3. They need to be triggered by actions such as @click and @change in the template. Like variables, the function name needs to be returned in the setup.

The following is a simple example for developers to understand more intuitively:

<template>
  <p>{
    
    {
    
     msg }}</p>

  <!-- 在这里点击执行 `return` 出来的方法 -->
  <button @click="updateMsg">修改MSG</button>
</template>

<script lang="ts">
import {
    
     defineComponent, onMounted, ref } from 'vue'

export default defineComponent({
    
    
  setup() {
    
    
    const msg = ref<string>('Hello World!')

    // 这个要暴露给模板使用,必须 `return` 才可以使用
    function updateMsg() {
    
    
      msg.value = 'Hi World!'
    }

    // 这个要在页面载入时执行,无需 `return` 出去
    const init = () => {
    
    
      console.log('init')
    }

    onMounted(() => {
    
    
      init()
    })

    return {
    
    
      msg,
      changeMsg,
    }
  },
})
</script>

Guess you like

Origin blog.csdn.net/m0_49515138/article/details/128249382