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

一.父传子(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.效果:

猜你喜欢

转载自blog.csdn.net/limif/article/details/126928766