Vue3 methods Property


Vue3 选项式 APIVue3 Options API

In Vue3,methodsThe property is an object used to define methods available in the component. These methods can be invoked in the component's template via event binding or other means.

methodsThe property is usually used to handle user interactions, execute certain logic operations, or trigger component behaviors.


Basic syntax for using the methods property

In a Vue3 component,methodsThe property is usuallysetupDefined outside the function. It contains an object, where each key-value pair represents a method: the key is the method name, and the value is the implementation of the method.

Example

export default {
  methods: {
    methodName() {
      // Method logic
    },
    anotherMethod() {
      // Logic of another method
    }
  }
}

Example: Triggering a method when a button is clicked

The following is a simple example showing how to use themethodsproperty to handle button click events.

Example

<template>
  <div>
    <button @click="handleClick">Click me</button>
    <p>{{ message }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
message: 'Hello, Vue3!'
    };
  },
  methods: {
    handleClick() {
this.message = 'The button has been clicked!';
    }
  }
};
</script>

Code Analysis

  1. Template section:

    • Using@clickevent bindinghandleClickassociates the method with the button's click event.
    • When the user clicks the button,handleClickthe method will be invoked.
  2. Script section:

    • dataThe function returns an object containing themessageproperty, which is used to store the displayed message.
    • methodsDefined in the object is ahandleClickmethod, which modifiesmessagethe value of.

Purpose of the methods property

  1. Handle user interactions:

    • methodsThe property is commonly used to respond to user interactions such as clicks, input, etc.
  2. Execute logic operations:

    • Complex logic code can be written in methods, such as data calculations, conditional judgments, etc.
  3. Trigger component behaviors:

    • Through method calls, behaviors such as component state updates and data requests can be triggered.

Differences between methods and computed

  • methods:

    • Every time it is called, the code in the method body is executed.
    • Suitable for event handling or operations that need to be triggered manually.
  • computed:

    • It will only be recalculated when the dependent data changes.
    • Suitable for scenarios where results need to be dynamically calculated based on data.

Exercise

  1. Try tomethodsadd a new method to clear themessagecontent of.
  2. Modify the example code so that the current time is displayed when the button is clicked.

Vue3 选项式 APIVue3 Options API

Other extensions