vue3组件父子传值的常见语法

184 阅读1分钟

vue3组件父子传值的常见语法

  1. props传值
    image.png
父组件代码
	<div class="wrap">
		<h1>vue常见传参方式</h1>
		<p>props传值</p>
		<!-- 通过v-bind动态传参 可以简写为:-->
		<childCmp :dataTitle="title"></childCmp>
	</div>
</template>
<script setup lang="ts">
// 引入api
import { ref } from "vue"
// 引入组件
import childCmp from "@/components/cmp/prop.vue"
let title=ref("测试数据")//创建动态数据
</script>
子组件代码
	<div class="child">
		<h1>我是子组件</h1>
		<p>父组件传递过来的数据:{{ dataTitle }}</p>
	</div>
</template>
<script setup>
//定义变量接受 在js区域访问 需要添加props前缀
const props = defineProps({
	dataTitle:String// 添加校验类型
});
</script>
<style scoped lang="scss">
	.child{
		width: 200px;
		height: 200px;
		background: skyblue;
	}
</style>

总结:

父子组件传值:父组件中调用子组件通过自定义属性传值 传值分为静态传参(字符串)和动态传参(数据),子组件内部通过defineProps()接受 或者通过setup(props){}接收