一、Options API 中的方法定义
在 Options API 中,方法定义在 methods
对象中,可以直接通过 this
访问组件实例的属性和其他方法。
1. 基本语法
export default {
data() {
return { count: 0 };
},
methods: {
increment() {
this.count++; // 直接修改响应式数据
},
greet(name) {
alert(`Hello, ${name}!`);
}
}
}
2. 模板中绑定方法
<template>
<button @click="increment">点击增加:{{ count }}</button>
<button @click="greet('Alice')">打招呼</button>
</template>
3. 事件对象访问
若需要访问原生 DOM 事件对象,使用 $event
:
<template>
<input @input="handleInput($event, '额外参数')" />
</template>
<script>
export default {
methods: {
handleInput(event, extraParam) {
console.log(event.target.value, extraParam);
}
}
}
</script>
4. 事件修饰符
Vue 提供便捷的事件修饰符:
<template>
<!-- 阻止默认行为 -->
<form @submit.prevent="handleSubmit">
<!-- 停止事件冒泡 -->
<div @click.stop="handleClick">
<!-- 按键修饰符 -->
<input @keyup.enter="submitForm" />
</template>
二、Composition API 中的方法处理
在 Composition API(使用 setup()
)中,方法直接在 setup
函数中定义,并通过返回对象暴露给模板。
1. 基本语法
<script>
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
// 定义方法
const increment = () => {
count.value++; // 注意 ref 需要使用 .value
};
const greet = (name) => {
alert(`Hello, ${name}!`);
};
return { count, increment, greet };
}
}
</script>
2. 使用响应式数据
通过 ref
或 reactive
创建响应式变量,方法中直接操作它们:
const state = reactive({ count: 0 });
const increment = () => {
state.count++;
};
3. 事件绑定
模板绑定方式与 Options API 一致:
<template>
<button @click="increment">{{ count }}</button>
</template>
三、方法的高级用法
1. 异步方法
在方法中使用 async/await
处理异步操作:
methods: {
async fetchData() {
try {
const response = await fetch('https://api.example.com/data');
this.data = await response.json();
} catch (error) {
console.error('请求失败:', error);
}
}
}
2. 自定义事件触发
通过 emit
向父组件传递事件:
<!-- 子组件 ChildComponent.vue -->
<script>
export default {
emits: ['custom-event'], // 声明自定义事件
methods: {
triggerEvent() {
this.$emit('custom-event', '参数值');
}
}
}
</script>
<!-- 父组件中使用 -->
<ChildComponent @custom-event="handleCustomEvent" />
3. 方法作为计算属性或监听器的依赖
在 Composition API 中,方法可以被 watch
或 computed
引用:
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
watch(count, (newVal) => {
console.log('count 变化:', newVal);
});
四、最佳实践与注意事项
-
避免箭头函数绑定
this
在 Options API 中,避免使用箭头函数定义方法,否则this
指向会丢失:// 错误示例 methods: { increment: () => this.count++ // this 指向错误! }
-
方法命名清晰
使用动词开头(如handleClick
、fetchData
),提高代码可读性。 -
逻辑复用
复杂逻辑可抽离为自定义 Hook(Composition API)或 Mixin(Options API)。 -
性能优化
高频事件(如滚动、输入)使用防抖(debounce)或节流(throttle):import { debounce } from 'lodash-es'; const handleInput = debounce(() => { // 处理逻辑 }, 300);
五、总结
- Options API:通过
methods
对象定义方法,适合简单组件。 - Composition API:在
setup()
中直接定义函数,适合复杂逻辑和复用。 - 事件修饰符:简化事件处理(如
.prevent
、.stop
)。 - 响应式数据操作:在方法中直接修改
ref
或reactive
变量。 - 异步处理:结合
async/await
管理异步流程。 - 自定义事件:通过
emit
实现父子组件通信。