父传子接:
父组件传值
<template>
<div>
<div>
我是父亲
<input type="text" v-model="a" />
</div>
<hr />
<child :info="parent" />
</div>
</template>
<script setup>
import child from "./child.vue";
import { ref } from "vue";
const a = ref("");
const parent = ref(a);
</script>
<style scoped>
</style>
子组件接收
<template>
<div>我是孩子 : {{ info }}</div>
</template>
<script setup>
import { toRefs, defineProps } from "vue";
const props = defineProps({
//子组件接收父组件传递过来的值
info: String,
});
//使用父组件传递过来的值
const { info } = toRefs(props);
</script>
<style scoped>
</style>
子传父接:
子组件传值: setup语法糖的是defineEmits
<template>
<div>我是子组件<input type="text" v-model="a" /></div>
</template>
<script setup>
import { defineEmits, ref } from "vue";
let a = ref("");
let param = {
content: a,
};
// 使用defineEmits创建名称,接受一个数组
const emit = defineEmits(["params"]);
//传递给父组件
emit("params", param);
</script>
<style>
</style>
父组件接收:
<template>
<div class="hello">
我是父组件
<p>子组件传递的值是 {{ result }}</p>
<hr />
<!-- clickChild是子组件绑定的事件,click是父组件接受方式 -->
<child @params="clickEven" />
</div>
</template>
<script setup>
import child from "./child.vue";
import { ref } from "vue";
const result = ref("");
const clickEven = (val) => {
result.value = val.content;
};
</script>
<style scoped>
</style>