Vue3語法糖-props父傳子

父元件程式碼如下

  • 新增子組件,引入子組件
  • 引入ref
  • 申明宣告父對子傳值數據
  • 在子組件將數據傳遞,:name="name" :list="lists"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
<div>
<child :name="name" :list="lists"/>
</div>
</template>

<script setup lang="ts">
import {ref} from 'vue'
// 引入子元件
import child from './child.vue'
const name = ref('小叮噹')
const lists = ref([
{id:110,name:'狂徒'},
{ id: 111, name: '上班族' },
{id:112,name:'自由業'}
])
</script>


子元件程式碼如下

  • 新增子組件,引入子組件
  • 引入defineProps(Vue3.2 版本后 defineProps 和 defineEmits 無需再導入)
  • 申明宣告props,欄位type
  • 在子組件將數據傳遞,:name="name" :list="lists"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<template>
<div>
<!--父對子傳值時-->
<span>{{props.name}}</span>
<ul>
<li v-for="(item, id) in list" :key="id">
{{ item.name }}
</li>
</ul>
</div>
</template>

<script setup lang="ts">
//Vue3.2 版本后 defineProps 和 defineEmits 無需再導入
//import { defineProps } from 'vue'
// 宣告props
const props = defineProps({
name: {
type: String,
default: '11'
},
list: {
type: Array,
default: '11'
}

})

</script>

父對子