vue3 语法之 父组件,子组件之间的数据传递

世事洞明皆学问,人情练达即文章。(《红楼梦》)
在这里插入图片描述

子组件使用v-model

父组件

// father.vue
<template>

    <div class="father">{{ fatherRef }}</div>

    <Child :fatherRef="fatherRef" @changeVal="changeVal"></Child>

</template>

<script setup lang="ts">

import { ref } from "vue";

import Child from "./Child.vue";

const fatherRef = ref("1");

function changeVal(val: string) {

    fatherRef.value = val;

}

</script>


<style lang="scss" scoped>

.father {

    margin-top: 40px;

    margin-bottom: 40px;

}

</style>

通过computed函数,set函数触发emit方法。get获取父组件传过来的fatherRef

// child.vue
<template>
	<input v-model="inputVal"/>
</template>
<script lang="ts" setup>
const props = defineProps<{fatherRef: String}>()
const emits = deineEmits(['changeVal'])
	const inputVal = computed({
		set:(val:String) => {
			emits('changeVal',val)
		},
		get: () => {
			return props.fatherRef
		}
    })
</script>

可以从父组件传递值和改变值的方法,然后子组件也可以使用v-model

例子中父组件传递 modelValue和update:modelValue方法 父组件

<template>

    <Child :modelValue="searchText" @update:modelValue="changeVal"> </Child>

</template>

<script setup lang="ts">

import { ref } from "vue";

import Child from "./Child.vue";

const searchText = ref(1);

function changeVal(val: number) {

    searchText.value = val;

}

</script>

<style lang="scss" scoped>

.father {

    margin-top: 40px;

    margin-bottom: 40px;

}

.btn {

    font-size: 20px;

    color: red;

}

</style>

子组件

<template>
    <input v-model="modelValue" />
</template>


<script setup lang="ts">

import { computed, useAttrs, useSlots } from "vue";

const props = defineProps<{

    modelValue: number;

}>();

// const emits = defineEmits(["changeVal"]);

</script>


<style lang="scss" scoped>

.child {

}

</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值