1. 父组件触发子组件的方法
父组件代码如下:
<template>
<div class="parent">
<button @click="getChild">触发子组件方法</button>
<!-- 1. 定义ref -->
<child ref="childRef"></child>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
import child from "@/components/child.vue";
export default defineComponent({
setup() {
// 2. 定义与ref同名变量
const childRef = ref<any>();
const getChild = () => {
// 3. 调用子组件的方法或者变量,通过value
childRef.value.doSomething();
}
return {
// 4. return 该变量
childRef,
getChild
};
},
components: {
child,
},
});
</script>
子组件代码如下:
<template>
<div class="child">
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
setup() {
// 1. 定义子组件的方法
const doSomething = () => {
console.log('已触发组件方法');
}
return {
// 2. return 该方法
doSomething
};
},
});
</script>
效果:
2.子组件触发父组件的方法
父组件代码如下:
<template>
<div class="parent">
<!-- 1. 接受方法名 -->
<child @postData="postData"></child>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import child from "@/components/child.vue";
export default defineComponent({
setup() {
// 2. 定义方法
const postData = () => {
console.log('触发父组件的方法');
}
return {
// 3. return 出来
postData
};
},
components: {
child,
},
});
</script>
子组件代码如下:
<template>
<div class="child">
</div>
</template>
<script lang="ts">
import { defineComponent, onMounted } from "vue";
export default defineComponent({
setup(props, context) {
const doSomething = () => {
// 与vue2不同的是要通过 context 来找到 emit
context.emit('postData');
}
onMounted(() => {
doSomething();
})
return {
};
},
});
</script>
效果如下:
Ps:1. 该测试环境为 vue3 + Ts
2. 如果需要传值和 vue2 类似