父子组件传值
- 注意ref获取要在合适的生命周期当中(等到DOM加载完成获取)
- 事件方法必须要return出去否则无法在实例上找到方法
<template>
<div>
父组件
<button @click="FatherClick">父组件按钮</button>
<Childs ref="childsDom"></Childs>
</div>
</template>
<script lang="ts">
import Childs from "./childs.vue";
import { ref } from "vue";
export default {
name: "",
components: { Childs },
setup(props, context) {
const childsDom: any = ref(null);
const FatherClick = () => {
childsDom.value.handelClick();
console.log(childsDom.value);
};
return {
FatherClick,
childsDom,
};
},
};
</script>
<template>
<div>
<button>子组件按钮</button>
</div>
</template>
<script lang="ts">
export default {
setup() {
const handelClick = () => {
console.log("@子组件----被调用了");
};
return {
handelClick,
};
},
};
</script>
<style scoped></style>
子组件调用父组件内部的方法
<template>
<div>
父组件
<button>父组件按钮</button>
<Childs @FatherClick="FatherClick"></Childs>
</div>
</template>
<script lang="ts">
import Childs from "./childs.vue";
import { ref } from "vue";
export default {
name: "",
components: { Childs },
setup(props, context) {
const FatherClick = () => {
console.log('@父组件----被调用了');
};
return {
FatherClick,
};
},
};
</script>
<template>
<div>
<button @click="handelClick">我是子组件按钮</button>
</div>
</template>
<script lang="ts">
export default {
emits: ["FatherClick"],
setup(props, context) {
const handelClick = () => {
context.emit("FatherClick");
};
return {
handelClick,
};
},
};
</script>
setup语法糖写法
父组件调用子组件内部的方法
<template>
<div>
父组件
<button @click="FatherClick">父组件按钮</button>
<div>----------华丽的分割线-----------</div>
<Childs ref="ChildsDom"></Childs>
</div>
</template>
<script setup lang="ts">
import Childs from "./childs.vue";
import { ref } from "vue";
const ChildsDom: any = ref(null);
const FatherClick = () => {
ChildsDom.value.handelClick();
console.log(ChildsDom.value);
};
</script>
<template>
<div>
<button>我是子组件按钮</button>
</div>
</template>
<script setup lang="ts">
const handelClick = () => {
console.log("@子组件----我被调用了");
};
defineExpose({
handelClick,
});
</script>
子组件调用父组件内部的方法
<template>
<div>
<button>父组件按钮</button>
<Childs @FatherClick="FatherClick"></Childs>
</div>
</template>
<script setup lang="ts">
import Childs from "./childs.vue";
import { ref } from "vue";
const ChildsDom: any = ref(null);
const FatherClick = () => {
console.log("@父组件----我被调用了");
};
function FatherClick(id, proLabel, val) {
console.log(id, proLabel, val);
};
</scripft>
<!-- 子组件 -->
<template>
<div>
<button @click="handelClick">我是子组件按钮</button>
</div>
</template>
<script setup lang="ts">
const emitsvva = defineEmits(["FatherClick"]);
const handelClick = (id, label, val) => {
emitsvva("FatherClick");
emitsvva('refreshCount', id, label, val);
};
</script>
<style scoped></style>