vue3.0脚手架setup内部的组件通信
1、父到子通过props
父组件
<template>
<div >
<Son data="currentRole.arr"></Son>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive} from "vue";
import Son from "../components/Son.vue";
export default defineComponent({
name: "father",
components: { Son },
setup() {
let currentRole = reactive({
arr: [{name:"小王",age:21}],
});
return { currentRole};
},
});
</script>
子组件
<template>
</template>
<script lang="ts">
import { onMounted } from "vue";
export default defineComponent({
props: {
data: {},
},
setup() {
const getData = () => {
console.log("传递的参数", props.data);
};
onMounted(() => {
getData ();
});
},
});
</script>
2、父到子通过provide和inject
父组件
<template>
<div >
<Son ></Son>
</div>
</template>
<script lang="ts">
import { provide, ref } from "vue";
import Son from "../components/Son.vue";
export default defineComponent({
name: "father",
components: { Son },
setup() {
provide("customVal", "我是父组件向子组件传递的值");
},
});
</script>
子组件
<template>
<div>
<h1>{{ customVal}}</h1>
</div>
</template>
<script lang="ts">
import { inject, ref } from "vue";
export default defineComponent({
setup() {
const customVal = inject("customVal");
return { customVal,};
},
});
</script>
3、父组件调用子组件的方法
父组件
<template>
<div >
<Son ref="RefChilde"></Son>
<div @click="fnCallChild">
点我调用Son组件里的方法
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
import Son from "../components/Son.vue";
export default defineComponent({
name: "father",
components: { Son },
setup() {
const RefChilde = ref(); //RefChilde 要和Son组件上的class名相同
const fnCallChild = () => {
RefChilde.value.sonFn(); //sonFn是子组件里的方法
};
return { RefChilde, fnCallChild };
},
});
</script>
子组件
<template>
<div>
<h1>{{ conts }}</h1>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
setup() {
const conts = ref("我是子组件");
const sonFn = () => {
conts.value = "我被父组件里调用了子组件的方法修改了数据";
};
return { conts, sonFn };
},
});
</script>
4、子组件调用父组件的方法
父组件
<template>
<Son @childToParent="childToParent"></Son>
</template>
<script>
import Son from "./components/Son.vue";
export default {
components: { Son },
setup(props) {
const childToParent = (msg) => {
console.log(msg);
};
return {
childToParent,
};
},
};
</script>
<style scoped>
</style>
子组件
<template>
<div style="border: 1px solid #ddd">
<button @click="handleClick">触发父组件方法</button>
</div>
</template>
<script>
export default {
name: "childrenComponent",
emits: ["childToParent"],
setup(props, { emit }) {
const handleClick = () => {
emit("childToParent", "传递消息");
};
return {
handleClick,
};
},
};
</script>
<style scoped>
</style>