Vue3 methods Property
In Vue 3,methods The property is an object used to define the methods available in a component. These methods can be called in the component's template via event binding or other means.
methods The property is typically used to handle user interactions, execute certain logic operations, or trigger component behavior.
Basic Syntax for Using the methods Property
In a Vue 3 component,methods the property is typically defined outside the setup function. It contains an object where each key-value pair represents a method: the key is the method name and the value is its implementation.
Example
export
default
{
methods
:
{
methodName
(
)
{
// Method logic
}
,
anotherMethod
(
)
{
// Logic of another method
}
}
}
Example: Trigger a Method on Button Click
The following is a simple example showing how to use the methods property to handle a button click event.
Example
Click me
{{ message }}
Code Analysis
-
Template Section:
@click event binding associates the handleClick method with the button's click event.handleClick method will be called.-
Script Section:
data The function returns an object containing message object property, which is used to store the message to display.methods The object defines the handleClick method, which modifies the message value.The Role of the methods Property
-
Handle User Interactions:
methods The property is commonly used to respond to user interactions such as clicks and inputs.-
Execute Logic Operations:
-
Trigger Component Behavior:
The Difference Between methods and computed
-
methods:
- executes the code in the method body every time it is called.
- is suitable for event handling or operations that need to be triggered manually.
-
computed:
- is only recalculated when its dependent data changes.
- is suitable for scenarios that require dynamically computing results based on data.
Exercise
- Try to add a new method in the
methodsto clearmessage. - Modify the example code so that clicking the button displays the current time.
Vue3 Options API