目录
提供默认属性名modelValue (或者使用v-model,子组件中仍然以modelValue为默认名)
仍需要props接收
提供默认事件update:modelValue
可使用fatherNum直接接收子组件传来的值后,在模板中直接使用
若需要对值进行其他操作,在这里用函数fromSon接收,其函数的第一个参数为传来的数据
父组件中
模板部分
【在父模板中的子组件标签上使用默认属性名modelValue,属性值为setup中的数据money】
<template>
<div class="container">
<h1>父组件:</h1>
{{ money }}
<div>子传父:{{ fatherNum }}</div>
<Son :modelValue="money" @update:modelValue="fatherNum = $event" />
<!-- <Son :modelValue="money" @update:modelValue="fromSon" /> -->
</div>
</template>
JS部分
<script>
import { ref } from "vue";
import Son from "./Son.vue";
export default {
components: {
Son,
},
setup() {
const money = ref(100);
const fatherNum = ref(0);
// // data为子组件传递过来的数据
// const fromSon = (data) => {
// fatherNum.value += data;
// };
return {
fatherNum,
money,
// fromSon,
};
},
};
</script>
子组件中
模板部分
<template>
<div>
<h1>子组件</h1>
<div>父传子:{{ modelValue }}</div>
<button @click="toSend">点击子组件按钮发送数据给父组件</button>
<hr />
</div>
</template>
JS部分
props属性中:子组件通过自定义属性名toSon拿到数据
<script>
import { ref } from "vue";
export default {
props: {
modelValue: {
type: Number,
default: 0,
},
},
setup(props, context) {
const num = ref(10);
const toSend = () => {
// 使用默认事件名 update:modelValue 第二个参数为传递的值
context.emit("update:modelValue", num.value);
};
return { toSend };
},
};
</script>
第二种父子传值,就到这了~