引言
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>
最后
如果本文对你有帮助,帮忙点个赞再走呗❤