vue3组件间通信几种方式 setup语法糖 -笔记

12 篇文章 0 订阅

一.父传子(prop)

1.父组件:cc.vue

<template>
    <div>
    <h2>组件通信的几种方式</h2>
        <div class="fatherOne">
            <div>
                <ccSonOne :msg2=msg2></ccSonOne>a
            </div>
        </div>
    </div>
</template>

<script setup>
import {ref} from "vue"
import ccSonOne from "../components/ccSonOne.vue"
const msg2 = ref("我是父亲") 
</script>

2.子组件:ccSonOne.vue

<template>
    <div>
        <span>我是c页面的一个儿子,我接受到父亲的动态值为:{{msg2}}</span>
    </div>
</template>

<script setup>
    const props = defineProps({
        msg2:{
            type:String,
            default:"hh"
        }
    })
</script>

3.效果:

二:子传父

1.父组件:cc.vue

<template>
    <div>
    <h2>组件通信的几种方式</h2>
        <div class="fatherOne">
            <div>
                <ccSonOne @sonData="getmsg" ></ccSonOne>
                <span>儿子传递过来的值:{{getData}}</span>
            </div>
        </div>
    </div>

</template>
<script setup>
import {ref} from "vue"
import ccSonOne from "../components/ccSonOne.vue"
const getData =  ref("2")
const getmsg = (sonData) => {
    getData.value = sonData
}
</script>

2.子组件:ccSonOne.vue

<template>
    <div>
        <button @click="sendmsg">点我给父亲传值</button>
    </div>
</template>
<script setup>
import {ref} from "vue"
const msg = ref("我是儿子")
const emit = defineEmits(['sonData'])
const sendmsg = () => {
    emit("sonData", msg.value)
}
</script>

3.效果:

点击前:

 

点击后:

 三.expose、ref(获取子组件属性和方法)

1.cc.vue

<template>
    <div>
    <h2>组件通信的几种方式</h2>
        <div class="fatherOne">
            <div>
                <ccSonOne ref="comp"></ccSonOne>
                <button @click="getAttribute">点击获取子组件的属性和方法</button>
                <br>
                <span>{{getAttributeData}}</span>
            </div>
        </div>
    </div>

</template>

<script setup>
import {ref} from "vue"
import ccSonOne from "../components/ccSonOne.vue"
const comp = ref(null)
const getAttributeData = ref("")
const getAttribute = () => {
    getAttributeData.value=comp.value.attributeone,
    comp.value.functionOne()
}
</script>

2.ccSonOne.vue

<template>
    <div>
    </div>
</template>

<script setup>
import {ref} from "vue"
const attributeone = ref("我是子组件属性")
const functionOne = () =>{
    console.log("我是子组件方法")
}
defineExpose({
    attributeone:attributeone.value,
    functionOne,
})
</script>

3.效果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值