vue3 props 05

文采呱呱發表於2024-03-13

父元件

<script setup lang="ts">
import person from '@/components/person.vue'
import { ref, reactive, defineProps } from 'vue'
import { type Person } from '@/types/index'
let personList = reactive<Person>([
    { id: '1', name: 'zhansan', age: 18 }
])
console.log(personList)
</script>

<template>
  <div>
    <person a="元件" b="要列印接收的引數只能把defineProps也一起列印" :list="personList"/>
  </div>
</template>

<style scoped></style>

  子元件

<script setup lang="ts">
import { ref, reactive, withDefaults } from 'vue'
import { type Person } from '@/types/index'
// 接收a
// defineProps(['a','b'])
// defineProps只接收
// let x = defineProps(['a', 'b','personList'])
// 接收list+限制型別
// defineProps<{list:Person}>()
// 接收list+限制型別+限制必要性+指定預設值
// defineProps<{ list?: Person }>()
// 終極寫法
withDefaults(defineProps<{ list?: Person }>(), {
    list:()=> [{
        id: '1111',
        name: 'lisi',
        age: 18
    }]
})
// 要列印接收的引數
// console.log(x)

</script>

<template>
    <div>
        <!-- <p>{{ a }}</p>
        <p>{{ b }}</p> -->
        <p>{{ list }}</p>
        <ul>
            <li v-for="(item, index) in list" :key="index">
                名字:{{ item.name }}
            </li>
        </ul>
    </div>
</template>

<style scoped></style>

  

相關文章