vue3 父组件【属性】传值给子组件【props】接收

 

父组件文件:parentcomponent.vue

子组件文件:childcomponent.vue

  1. 传普通值
  2. 传动态值
  3. 传对象
  4. 传数组
<!-- 父组件 -->
<template>
   <h1>I am ParentComponent</h1>
   <ChildComponent msg="nice"/>
  </template>
<script setup>
   import ChildComponent from './ChildComponent.vue'
</script>
 

一、传普通值

<!-- 父组件 -->
<template>
  <h1>I am ParentComponent</h1>
  <ChildComponent msg="nice"/>
</template>
<script setup>
  import ChildComponent from './ChildComponent.vue'
</script>
 
 
<!-- 子组件 -->
<template>
   <h2>I am ChildComponent</h2>
   <p>I want {{ props.msg }} from my Parent.</p>
</template>
<script setup>
   import { defineProps } from 'vue';
const props = defineProps({ msg:String, })
</script>

二、传动态值

<!-- 父组件 -->
<template>
   <h1>I am ParentComponent</h1>
   <ChildComponent :msg="message"/>
</template>
 
<script setup>
  import ChildComponent from './ChildComponent.vue'
  const message = "动态传值"
</script>
 
 

可能会有疑惑,defineProps是什么呢?

它其实就是一个API函数。defineProps 是 Vue 3 中的一个函数,用于定义组件的 props。与 Vue 2 中的 props 配置选项不同,使用 defineProps 函数定义的 props 是只读的响应式对象,它们的值由父组件传递而来,不能被子组件修改。这有助于提高组件的可维护性和可重用性,并减少不必要的副作用。 简单理解:就是用于拿父组件传过来的值,且子组件不能修改!

 

三、传数组

<!-- 父组件 -->
<template>
   <h1>I am ParentComponent</h1>
   <ChildComponent :arrMsg="A"/>
</template>
<script setup>
  import ChildComponent from './ChildComponent.vue'
  const A = [
     {id:1,name:'Kiangkiang'},
     {id:2,name:'Xiaohong'},
     {id:3,name:'Xiaoma'}
   ]
</script>
 
<!-- 子组件 -->
<template>
   <h2>I am ChildComponent</h2>
   <h3>数组</h3>
   <ul v-for="item in props.arrMsg" :key="item.id">
   <li>{{ item.id }}-{{ item.name }}</li>
</ul>
</template>
<script setup>
   import { defineProps } from 'vue';
   const props = defineProps({
     arrMsg:Array//接收父组件ParentComponent传过来的数组
  })
</script>
 

四、传对象

<!-- 父组件 -->
<template>
   <h1>I am ParentComponent</h1>
   <ChildComponent :list="ListMsg"/>
</template>
<script setup>
  import ChildComponent from './ChildComponent.vue'
  const ListMsg = {
     name:'Xiaoma', age:'18', gender:'Boy',
   }
</script>

 
<!-- 子组件 -->
<template>
   <h2>I am ChildComponent</h2>
   <h3>个人信息</h3>
<ul>
   <li>{{ props.list.name }}</li>
   <li>{{ props.list.age }}</li>
   <li>{{ props.list.gender }}</li>
</ul>
</template>
<script setup>
   import { defineProps } from 'vue';
  const props = defineProps({
     list:Object,
   })
</script>

 

 

 

posted @ 2024-07-04 14:58  林财钦  阅读(7)  评论(0编辑  收藏  举报