component组件如何实现页面切换 vue3搭配typescript

我这边是因为 登录 注册 注册信息完善三个页面背景图一样 所以想到了用component组件去做页面切换。

页面跳转逻辑是 登录跳转到注册 注册跳转到注册信息完善页面

这是我的layout页面 通过layoutPath变量的值改变去达到切换组件的目的

三个子组件通过子传父的方式调用方法clickChange去修改layoutPath的值

这里是很简单

但是用到了vue3+typescript 就不简单了

我先了解了一下vue3中 是通过setup 中的 context属性

context.emit 去做的子传父

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用动态组件和props来实现根据参数加载不同的组件。具体实现步骤如下: 1. 定义组件props来接收参数,例如: ```typescript interface ComponentProps { componentType: string; } ``` 2. 在父组件模板中使用动态组件,并根据传入的参数设置不同的组件。例如: ```vue <template> <component :is="currentComponent" :componentType="componentType" /> </template> <script> import ComponentA from './ComponentA.vue'; import ComponentB from './ComponentB.vue'; export default { components: { ComponentA, ComponentB, }, props: { componentType: String, }, computed: { currentComponent() { switch (this.componentType) { case 'typeA': return 'ComponentA'; case 'typeB': return 'ComponentB'; default: return null; } }, }, }; </script> ``` 在上面的代码中,我们通过computed属性根据传入的componentType参数来返回对应的组件component标签的is属性用于设置当前渲染的组件。 3. 在子组件中使用props接收参数,例如: ```vue <template> <div>{{ componentType }} component</div> </template> <script> import { defineComponent, PropType } from 'vue'; interface ComponentProps { componentType: string; } export default defineComponent({ props: { componentType: { type: String as PropType<ComponentProps['componentType']>, required: true, }, }, }); </script> ``` 在上面的代码中,我们使用defineComponent函数定义了子组件,并通过props接收了componentType参数。 最后,你可以在父组件模板中使用这个动态组件,并传入不同的componentType参数,例如: ```vue <template> <div> <button @click="showTypeA">Show Component A</button> <button @click="showTypeB">Show Component B</button> <component-loader :componentType="currentComponentType" /> </div> </template> <script> import ComponentLoader from './ComponentLoader.vue'; import { defineComponent, reactive } from 'vue'; interface AppData { currentComponentType: string; } export default defineComponent({ components: { ComponentLoader, }, setup() { const data = reactive<AppData>({ currentComponentType: '', }); function showTypeA() { data.currentComponentType = 'typeA'; } function showTypeB() { data.currentComponentType = 'typeB'; } return { ...data, showTypeA, showTypeB, }; }, }); </script> ``` 在上面的代码中,我们定义了一个父组件,并在模板中使用了两个按钮来切换显示不同的组件。通过修改currentComponentType属性来切换显示不同的组件

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值