Vue3 组件通信$refs,$parent

首次发布:2023-12-30 20:54

父组件与子组件通讯

父组件App.vue

<template>
  <div>
    <p>{{ money }}</p>
    <button @click="updateUserInfo">修改</button>
  </div>
  <clildd ref="c1" />
  <clildd2 ref="c2" />
</template>
<script setup lang="ts">
import { ref } from 'vue'
import clildd from '@/components/Child.vue'
import clildd2 from '@/components/Child2.vue'
let c1 = ref()
let c2 = ref()

function updateUserInfo() {
  c1.value.cName = '罗分明'
  c1.value.test('调用子组件的方法')
  c2.value.cName = '罗分明个人博客'
}
//获取所有子组件对外的数据, 方法调用
function getAllChild(refs: any) {
  console.log(refs);
  for (let key in refs) {
    refs[key].cName += '_已修改'
  }
}

let money = ref(10000)
//把数据交给外部  参数可以是 字段属性 也可以是方法
defineExpose({ money, pTest })
function pTest(msg: string) {
  console.log(msg)
}
</script>
<style scoped></style>

子组件1 /components/Child.vue

<template>
    <div class="child">
        <p>
            {{ cName }}
        </p>
        <button @click="updateP($parent)">修改父组件方法</button>
    </div>
</template>
<script setup lang="ts" >
import { ref } from 'vue';
let cName = ref('LuoFenMing');
function test(msg: string) {
    console.log(msg)
}
//把数据交给外部  参数可以是 字段属性 也可以是方法
defineExpose({ cName, test })



function updateP(parent: any) {
    parent.money += 10
    parent.pTest('调用父组件方法')
}
</script>

<style>
.child {
    border: 1px red solid;
}
</style>

子组件2 /components/Child2.vue

<template>
    <div class="child2">
        <p>
            {{ cName }}
        </p>
    </div>
</template>
<script setup lang="ts" >
import { ref } from 'vue';
let cName = ref('www.luofenming.com');
//把数据交给外部 参数可以是 字段属性 也可以是方法
defineExpose({ cName })
</script>

<style>
.child2 {
    border: 1px blue solid;
}
</style>

本文来自 www.luofenming.com