一、Vue 3 調用子組件方法 child
在 Vue 3 中,為了更好的拆分組件,允許我們定義一個子組件,並且可以通過組件標籤的方式去使用它。在像這種組件中,子組件方法調用就顯得很重要。在這種情況下,可以使用 $refs 屬性來選擇子組件,並且調用其方法。
const ChildComponent = {
methods: {
hello() {
console.log('Hello from ChildComponent!');
}
}
}
export default {
components: { ChildComponent },
methods: {
callChildMethod() {
this.$refs.child.hello();
}
}
}
二、Vue 3 調用子組件函數
在 Vue 3 中,函數不再作為組件的方法存在。新的組件函數實際上作為子組件子組件實例的屬性,可以通過訪問該屬性名來調用子組件函數。
const ChildComponent = {
setup() {
const sayHello = () => {
console.log('Hello from ChildComponent Function!');
}
return { sayHello };
}
}
export default {
components: { ChildComponent },
methods: {
callChildFunction() {
this.$refs.child.sayHello();
}
}
}
三、Vue 3 父組件調用子組件方法
有時我們需要在父組件中去調用子組件方法。Vue 3 給我們提供了可用性 API ,即 provide 和 inject。在父組件中,通過 provide 向下傳遞數據或者方法,在子組件中通過 inject 可以獲取到數據或者方法。
const ChildComponent = {
setup(props, { expose }){
const sayHello = () => {
console.log('Hello from ChildComponent Function!');
}
expose({ sayHello })
// or
return { sayHello };
}
}
const ParentComponent = {
components: { ChildComponent },
methods: {
callChildMethod() {
this.$refs.child.sayHello();
}
},
setup() {
return { sayHello: inject('sayHello') }
}
}
四、Vue 3 ts 調用子組件方法
在 Vue 3 中,我們可以使用 TypeScript 去定義組件並且更好地支持類型檢查。在 TypeScript 中調用子組件方法與 JavaScript 中大體相同,需要在 Vue 組件 TypeScript 類型定義中定義 ref 屬性,然後可以使用它來調用子組件方法。
import { defineComponent, ref } from 'vue';
const ChildComponent = defineComponent({
methods: {
hello() {
console.log('Hello from ChildComponent!');
}
}
});
export default defineComponent({
components: { ChildComponent },
setup() {
const childRef = ref(null);
return { childRef };
},
methods: {
callChildMethod() {
this.childRef?.hello();
}
}
});
五、Vue 3 父組件調用子組件方法
在 Vue 3 中,父組件調用子組件方法也有兩種方式。一種是直接在父組件中獲取到子組件實例引用,通過該引用調用子組件方法;另外一種是使用 provide / inject 的方式進行傳遞。提前告訴大家,第一種方式比較限制,不如第二種方式做得好。
import { defineComponent, ref } from 'vue';
const ChildComponent = defineComponent({
methods: {
hello() {
console.log('Hello from ChildComponent!');
}
}
});
export default defineComponent({
components: { ChildComponent },
setup() {
const childRef = ref(null);
return { childRef };
},
mounted() {
this.childRef = this.$refs.child;
},
methods: {
callChildMethod() {
this.childRef?.hello();
}
}
});
六、Vue 3 子組件調用父組件方法
在 Vue 3 中,子組件如何調用父組件的方法與 Vue 2 中基本相同,但也有一些細微的變化。我們可以向上通過 emit 事件傳遞數據,使得父組件可以接收到子組件傳遞的數據。
const ChildComponent = {
methods: {
handleClick() {
this.$emit('hello');
}
}
}; const ParentComponent = {
components: { ChildComponent },
methods: {
sayHello() {
console.log('Hello from ParentComponent!');
}
},
template: '
原創文章,作者:YBRX,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/141993.html