Vue3父子组件传值相关

vue3.2中父组件调用子组件中的方法、父子组件传值

总结

1、父组件调用子组件中的方法,子组件需主动暴露出来,父组件才可调用 defineExpose

子组件 child.vue

  <script setup>
        const childMethod = () => {
            console.log('child method.')
        }

        // 主动暴露childMethod方法
        defineExpose({ childMethod })
    </script>

父组件

  <script setup>
        import { ref } from 'vue'
        import child from './child.vue'

        const childRef = ref()

        const callChildMethod = () => {
        childRef.value.childMethod()
        }
    </script>
<template>
    <child ref="childRef"></child>
    <button @click="callChildMethod">call</button>
</template>

2、 父子组件传值,使用 defineProps 和 defineEmits API 来替代 props 和 emits

父组件向子组件传参:

//父组件

    <template>
         <div>父组件</div>
         <Child :title="msg" />
    </template>
    ​
    <script setup>
        import {ref} from 'vue'
        import Child from './child.vue'
        const msg = ref('父的值')  //自动返回,在template直接解套使用
    </script>

//子组件

   <template/> 中可以直接使用父组件传递的props (可省略props.)
    <script-setup> 中需要通过props.xx获取父组件传递过来的props

    <template>
         <div>子组件</div>
         <div>父组件传递的值:{{title}}</div>
    </template>
  <script setup>
        //import {defineProps} from 'vue'   不需要引入
        ​
        //语法糖必须使用defineProps替代props
        const  props = defineProps({
             title: {
               type: String,
               default:''
            }
        });

        //script-setup中需要通过props.xx获取父组件传递过来的props
        console.log(props.title) //父的值
    </script>

3、子组件向父组件传递数据(子组件向外暴露数据):

//子组件

 <template>
         <div>子组件</div>
         <button @click="toEmits">子组件向外暴露数据</button>
    </template>
   <script setup>
        import {ref} from 'vue'
        const name = ref('我是子组件')

        const  emits = defineEmits(['childFn']);//1、暴露内部数据
        ​
        const  toEmits = () => {
             emits('childFn',name) //2、触发父组件中暴露的childFn方法并携带数据
        }
  </script>

//父组件

 <template>
         <div>父组件</div>
         <Child  @childFn='childFn' />
         <p>接收子组件传递的数据{{childData}} </p>
    </template>
    ​
    <script setup>
        import {ref} from 'vue'
        import Child from './child.vue'
           
        const childData = ref(null)    
        const childFn=(e)=>{
           console.log('子组件触发了父组件childFn,并传递了参数e')
           childData=e.value
        }    
         
    </script>
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值