vue3 父组件引用子组件,子组件调用父组件的方法来实现父组件的组件切换

  1. 首先创建子组件

src/components/Child.vue

<script setup lang="ts">
// 接受父组件传入过来的事件 让子组件能够调用父组件 实现子父通信
let emits = defineEmits(["toggle"]);
// 发送事件到父组件
const emitToggle = (component:string) => {
  // 发送事件到父组件
  emits('toggle', component);
};
</script>

<template>
<!--  子组件的菜单按钮  -->
  <button @click="emitToggle('UserProfile')">显示用户概述组件</button>
  <button @click="emitToggle('UserPosts')">显示用户帖子组件</button>

</template>

<style scoped>

</style>
  1. 在父组件引用 子组件 来实现局部刷新父组件中的内容
src/App.vue
 <template>
  <!-- 父组件中的布局 -->
      <!-- toggle:事件名   toggleComponent:具体事件  -->
    <Child @toggle="toggleComponent"></Child>


    <component  :is="currentComponent"></component>

</template>

<script setup>
import { shallowRef} from 'vue';
import Child from "./components/Child.vue";
import UserProfile from "./components/UserProfile.vue";
import UserPosts from "./components/UserPosts.vue";

// shallowRef:Vue 只会对这个引用的顶层数据进行响应式转换
// 默认展示UserProfile (避免性能开销所以使用shallowRef)
//例如:const obj = { count: 0 }; const shallowObj = shallowRef(obj);,在这里修改 obj 中的属性不会触发重新渲染,但修改 shallowObj.value 中的属性会触发重新渲染。
const currentComponent = (shallowRef(UserProfile));

// 切换显示的组件
const toggleComponent = (component) => {
  if (component === 'UserProfile') {
    currentComponent.value = UserProfile;
  } else if (component === 'UserPosts') {
    currentComponent.value = UserPosts;
  }
};
</script>

运行效果:
在这里插入图片描述
总结:如果你想控制父组件的组件切换,而切换的按钮或者菜单被在父组件里封装成子组件 就可以使用这个方式 。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值