Vue3| 组合式 API 下的父传子

发布时间 2023-10-14 10:35:31作者: 嘎嘎鸭2

步骤:

一、父给子传 写死的值

1. 父组件中给子组件 以添加属性的方式传值

<script  setup>

import  sonComVue  from  './son-com.vue'   // 局部注册

</script>

 

<template>

<sonComVue  message = "黑马程序员"> </sonComVue>

</template>

2. 子组件内部通过 props 选项接收

(由于写了 setup,所以无法直接配置  props 选项,需要通过 defineProps "编译器宏" 接收子组件传递的数据)

注:<script>里使用 props 传递过来的数据要用 props.message;<template>里使用 props 传递过来的数据用 {{ message }}

<script  setup>

const  props = defineProps ({

      message : String

})

</script>

 

<template>

{{ message }}

</template>

 

 

二、父给子传 响应式数据

1. 父组件中给子组件 以添加属性的方式传值

<script  setup>

import  { ref }  from  'vue'

import  sonComVue  from  './son-com.vue'   // 局部注册

const  money = ref (100)

</script>

 

<template>

<sonComVue   : money = "money" > </sonComVue>

</template>

 

2. 子组件内部通过 props 选项接收

(由于写了 setup,所以无法直接配置  props 选项,需要通过 defineProps "编译器宏" 接收子组件传递的数据)

注:<script>里使用 props 传递过来的数据要用 props.money;<template>里使用 props 传递过来的数据用 {{ money }}

<script  setup>

const  props = defineProps ({

      money : Number

})

</script>

 

<template>

{{ money }}

</template>