Vue3父子组件间数据传值

1. props:父组件传递数据给子组件

(1)父组件Parent

<!-- 父组件Parent-->
<template>
  <div>
    <Children :message="parentMessage" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import Children from './Children .vue';

const parentMessage = ref('父组件传递的message');
</script>

(2)子组件Children

<!-- 子组件 Children-->
<template>
  <div>
    <p>父组件传递: {{ message }}</p>
  </div>
</template>

<script setup>
defineProps({
  message: {
    type: String,
    required: true
  }
});
</script>

2.emit:子组件传递数据给父组件

(1)子组件Children

<!-- 子组件 Children-->
<template>
  <button @click="sendDataToParent">点击我传递数据给父组件</button>
</template>

<script setup>
const emit = defineEmits(['childEvent']);

const sendDataToParent = () => {
  emit('childEvent', '来着子组件的数据');
};
</script>

(2)父组件Parent

<!-- 父组件 Parent -->
<template>
  <div>
    <Children @childEvent="handleChildEvent" />
    <p>来着子组件数据: {{ childData }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import Children from './Children.vue';

const childData = ref('');

const handleChildEvent = (data) => {
  childData.value = data;
};
</script>

3.v-model :双向数据绑定

(1)父组件Parent

<!-- 父组件 Parent -->
<template>
  <div>
    <Children v-model:message="count" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import Children from './Children.vue';

const count= ref(0)
</script>

(2)子组件Children

<!-- 子组件 Children-->
<template>
    <div>{{count}}</div>
  <button @click="localCount++">点我+1</button>
</template>

<script setup>
const props = defineProps({
  title: String,
  count: Number
})

const emit = defineEmits([ 'update:count'])

const localCount = ref(props.count)

watch(localCount, (newVal) => {
  emit('update:count', newVal)
})
</script>

4.ref:父组件调用子组件方法

(1)子组件Children

<!-- 子组件 Children -->
<template>
  <div>子组件</div>
</template>

<script setup>
const childMethod = () => {
  console.log('子组件方法被调用')
}

// 暴露给父组件的方法
defineExpose({
  childMethod
})
</script>

(2)父组件Parent

<!-- 父组件 Parent -->
<template>
  <Childrent ref="ChildrentRef" />
  <button @click="callChildMethod">调用子组件方法</button>
</template>

<script setup>
import { ref } from 'vue'
import ChildrentReffrom './Childrent .vue'

const childRef = ref(null)

const callChildMethod = () => {
  ChildrentRef.value.childMethod()
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值