vue3.0组件之间通信

引言

vue中通信传值的方法有很多,这里只列举下最常用的几种传值引用方法,搭配script setup 语法糖使用

一、父组件传值子组件

父组件
<template>
    <!-- 子组件 -->
    <Child :propData="propData" />
</template>

<script setup lang="ts">
    import { reactive, ref } from 'vue'
    import Child from './Child'

    const propData = ref({name:'john',age:18})
</script>
子组件接收
<template>
  <span>姓名:{{props.propData.name}}</span>
  <span>年龄:{{props.propData.age}}</span>
</template>

<script setup lang="ts">
import { defineProps } from "vue";//此处可以不写

const props = defineProps({
  propData: {
    type: Object,
    default: () => {},
  },
});
</script>

二、子组件传值给父组件

父组件
<template>
  <!-- 子组件 -->
  <Child @handleEmit="parentEdit" />
</template>

<script setup lang="ts">
const parentEdit = (val) => {
  console.log(val); //true
  // do something.....
};
</script>
子组件
<template>
  <span>我是子组件</span>
  <button @click="getClick">点击</button>
</template>

<script setup lang="ts">
import { defineEmits } from "vue"; //此处可以不写
// 定义声明会触发的事件
const emit = defineEmits(["handleEmit"]);

const getClick = () => {
  emit("handleEmit", true);
};
</script>

三、通过ref获取子元素中的值和方法

父组件
<template>
  <h1>我是父组件</h1>
  <!-- 子组件 -->
  <Child ref="child" />
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
const child = ref(null);

onMounted(() => {
  // 此时可以获取到dom节点信息
  console.log("获取dom元素", child.value);
});

const handleClick = () => {
  // 获取child中的属性
  console.log(child.isShow); //true
  // 调用child中的方法
  child.childFunc();
};
</script>
子组件
<template>
  <h1>我是子组件</h1>
</template>

<script setup lang="ts">
import { defineExpose, ref } from "vue";

const childFunc = () => {};
const isShow = ref(true);

//将需要用到的属性方法暴露出来
defineExpose({
  isShow,
  childFunc,
});
</script>

最后

如果本文对你有帮助,帮忙点个赞再走呗❤

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值