vue2調用子組件函式 - daniel-qa/Vue GitHub Wiki
vue2調用子組件函式
假設你有一個子組件,它有一個簡單的計數器和一個「重置」按鈕。父組件想要在不直接點擊子組件按鈕的情況下,也能控制重置這個計數器。
主要調用部分
refs 後面接的是 子組件的 ref名稱
this.$refs.myChild.resetCounter();
- 1 . 子組件 (ChildComponent.vue)
這個組件包含一個計數器和一個用於顯示的按鈕。最重要的部分是,我們定義了一個 resetCounter() 方法,這個方法就是我們希望父組件能調用的。
<template>
<div>
<h3>子組件:計數器</h3>
<p>目前的數字是:{{ count }}</p>
<button @click="count++">點我增加</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
};
},
methods: {
// 讓父組件能呼叫的方法
resetCounter() {
this.count = 0;
console.log('計數器已重置!');
}
}
};
</script>
- 2 . 父組件 (ParentComponent.vue)
在父組件中,我們引入子組件,並在子組件的標籤上加上 ref="myChild"。然後,我們在一個按鈕的點擊事件中,使用 this.$refs.myChild 來調用子組件的 resetCounter() 方法。
<template>
<div>
<h2>父組件</h2>
<ChildComponent ref="myChild" />
<hr>
<button @click="resetChildCounter">
在父組件點我,重置子組件的計數器
</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
resetChildCounter() {
// 3. 使用 this.$refs 存取子組件實例,並調用其方法
this.$refs.myChild.resetCounter();
}
}
};
</script>
- 範例說明
ref="myChild" 就像是為這個 ChildComponent 實例取了一個專屬的 ID。
當你在父組件中呼叫 resetChildCounter() 方法時,this.$refs.myChild 會指向這個子組件的實例。
你可以直接透過這個實例,調用子組件內部定義的任何方法,例如 resetCounter()。
這個方法的好處是,父組件可以主動控制子組件的行為,這在需要執行一些操作(如清除表單狀態、觸發驗證或啟動動畫)時非常有用。