《vue3同组件调用方法》
解决方案
在Vue 3中,如果要在同一个组件内部调用方法,可以通过直接使用this.方法名
(在选项式API中)或组合式API中的相应方式来实现。这有助于我们组织代码逻辑,让一个方法根据特定条件或事件触发另一个方法,从而完成更复杂的功能操作。
一、选项式API实现
在选项式API中,所有的方法都定义在methods
选项内。
```html
export default {
methods: {
firstMethod() {
console.log('这是个方法');
// 调用第二个方法
this.secondMethod();
},
secondMethod() {
console.log('这是第二个方法');
}
}
}
``
firstMethod
在这个例子中,当点击按钮时,会先执行方法,在该方法内部通过
this.secondMethod()调用了
secondMethod`方法。
二、组合式API实现
(一)使用setup函数内的普通函数定义
```html
import { defineComponent } from 'vue'
export default defineComponent({
setup() {
const firstFunc = () => {
console.log('这是个函数');
secondFunc();
}
const secondFunc = () => {
console.log('这是第二个函数');
}
return {
firstFunc
}
}
})
``
setup`函数内,然后在一个函数内部直接调用另一个函数即可。
这里将两个函数直接定义在
(二)使用ref或reactive定义可响应式的标志位来间接调用
```html
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const isTriggered = ref(false);
const triggerMethod = () => {
console.log('触发了');
isTriggered.value = true;
}
const watchIsTriggered = () => {
if (isTriggered.value) {
console.log('这是第二个被调用的函数');
isTriggered.value = false;
}
}
watchIsTriggered(); // 可以根据需要调整调用时机
return {
triggerMethod
}
}
})
```
这种方式适合一些比较复杂的场景,例如根据某些状态的变化来决定是否调用某个方法等。