qiankun实现子应用切换到子应用传递参数

文章介绍了在Qiankun框架下如何实现在React、Vue和Umi子应用之间的切换,并详细展示了如何在不同类型的子应用间传递参数,包括重写路由跳转方法和接收传递参数的细节。
摘要由CSDN通过智能技术生成

qiankun实现子应用切换到子应用传递参数

qiankun 子应用切换到子应用

基座重写跳转方法 基座 => App.tsx

import { useState } from 'react';
import './App.css';
import { Layout, Menu } from 'antd';
import { Link, Routes, Route } from 'react-router-dom';
import routes from './routes';
import Home from './pages/Home';

const { Sider, Header, Content } = Layout;

function App() {
  const currentPath = window.location.pathname; // 当前path
  // 当前选择菜单
  const [selectedPath, setSelectedPath] = useState(
    routes.find(item => currentPath.includes(item.key))?.key || ''
  );

  // 重写函数
  const _wr = function (type: string) {
    const orig = (window as any).history[type]
    return function () {
      const rv = orig.apply(this, arguments)
      const e: any = new Event(type)
      e.arguments = arguments
      window.dispatchEvent(e)
      return rv
    }
  }
  // 绑定事件
  window.history.pushState = _wr('pushState')

  // 在这个函数中做跳转后的逻辑
  const bindHistory = () => {
    const currentPath = window.location.pathname;
    setSelectedPath(
      routes.find(item => currentPath.includes(item.key))?.key || ''
    )
  }

  // 绑定事件
  window.addEventListener('pushState', bindHistory)

  return (
    <Layout>
      <Sider collapsedWidth="0">
        <img src="https://www.itheima.com/images/logo.png" className='page-logo' alt="" />
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={['main-app']}
          selectedKeys={[selectedPath || 'main-app']}
          onClick={({ key }) => setSelectedPath(key)}
        >
          {
            routes.filter((item) => item.showMenu).map(route => {
              return (
                <Menu.Item key={route.key}>
                  <Link to={route.path}>
                    {route.title}
                  </Link>
                </Menu.Item>
              );
            })
          }
        </Menu>
      </Sider>
      <Layout>
        <Header style={{ padding: 0 }} />
        <Content style={{ margin: '24px 16px 0', height: '100%', background: '#fff', padding: '24px' }}>
          {/* 主应用渲染区域 */}
          <Routes>
            <Route path="/" element={<Home />} />
          </Routes>

          {/* 子应用渲染区域 */}
          <div id='sub-app'></div>
        </Content>
      </Layout>
    </Layout>
  );
}
export default App;

切换到vue子应用的操作

react子应用 到vue页 + 到vue传递参数

import './App.css';
import { Link, Routes, Route } from 'react-router-dom'
import List from './pages/List';
import Detail from './pages/Detail';

function App() {

  const goVue = () => {
    window.history.pushState({}, '', '/sub-vue')
  }
  const goVueDetails = () => {
    const data = { name: '小小亮', id: 1 };
    window.history.pushState(data, '', `/sub-vue/detail?name=${data.name}&id=${data.id}`);
  };
  return (
    <div className="App">
      <h2>react 子应用</h2>
      <div className='menu'>
        <Link to={'/'}>list</Link>
        <Link to={'/detail'}>detail</Link>
        <a onClick={goVue}>vue列表页</a>
        <a onClick={goVueDetails}>vue详情页</a>
      </div>
      <Routes>
        <Route path='/' element={<List />} />
        <Route path='/detail' element={<Detail />} />
      </Routes>
    </div>
  );
}
export default App;

vue子应用 details详情页面 接受传递的参数

<template>
  <div>Detail
    <div>
      name-{{ name }}
      id - {{ id }}
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref} from "vue"
import { useRoute } from 'vue-router';
const route = useRoute();
console.log('route', route);
const name:any = ref('')
const id:any = ref('')
name.value = route.query.name;
id.value = route.query.id;

</script>

切换到umi子应用的操作

react子应用 umi子应用 详情页并且传递参数

function App() {
  const goUmiDetails = () => {
    const data = { name: '小小飞', id: 2 };
    window.history.pushState(data, '', `/sub-umi/detail?name=${data.name}&id=${data.id}`);
  }
  return (
    <div className="App">
      <h2>react 子应用</h2>
      <div className='menu'>
        <a onClick={goUmiDetails}>umi详情页</a>
      </div>
    </div>
  );
}

export default App;

umi子应用 details详情页面 接受传递的参数

const Detail = () => {
  const searchParams = new URLSearchParams(window.location.search);
  const id: string | null = searchParams.get("id");
  const name: string | null = searchParams.get("name");
  console.log("详情参数:", id, "name", name);
  return (
    <div>
      <p>详情页内容</p>
      <p>
        name-{name} id-{id}
      </p>
    </div>
  );
};

export default Detail;

.umirc.ts

import { defineConfig } from 'umi';

export default defineConfig({
  base: '/sub-umi',
  npmClient: 'npm',
  plugins: ['@umijs/plugins/dist/qiankun'],
  qiankun: {
    slave: {},
  },
  headScripts: [
    { src: 'https://unpkg.com/axios@1.1.2/dist/axios.min.js', ignore: true },
  ],
  routes: [
    { path: '/', component: '@/pages/index' },
    { path: '/detail', component: '@/pages/detail' },
  ],
});
  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Qiankun 中,应用内部路由的实现方式,主要有两种: 1. 应用使用自己的路由系统:应用可以使用自己的路由系统,例如 Vue Router、React Router 等,在应用中完成路由跳转和页面渲染。这种方式下,主应用只需要将应用加载到指定的容器中,不需要关心应用内部的路由实现。 2. 应用使用主应用的路由系统:应用可以使用主应用的路由系统,例如主应用使用 Vue Router 实现路由,应用可以使用 Vue Router 进行路由跳转和页面渲染。这种方式下,主应用需要将应用加载到指定的容器中,并且在主应用的路由表中配置应用的路由规则。 下面是第二种方式的代码示例: 首先,我们需要在主应用的路由表中配置应用的路由规则: ```javascript import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); const routes = [ { path: '/app1', component: () => import('@/views/App1.vue'), children: [ { path: '/app1/page1', name: 'page1', component: () => import('app1/Page1.vue'), }, { path: '/app1/page2', name: 'page2', component: () => import('app1/Page2.vue'), }, ], }, ]; const router = new VueRouter({ routes, }); export default router; ``` 在上述代码中,我们在主应用的路由表中定义了 `/app1` 的路由规则,并配置了两个路由 `/app1/page1` 和 `/app1/page2`,路由的组件分别位于应用 `app1` 中的 `Page1.vue` 和 `Page2.vue`。 然后,在应用中,我们需要使用 `history` 模式,并在路由模式中加上应用的前缀,例如 `/app1`: ```javascript import Vue from 'vue'; import VueRouter from 'vue-router'; import App from './App.vue'; Vue.config.productionTip = false; let instance = null; function render(props = {}) { const { container, routerBase } = props; const router = new VueRouter({ base: window.__POWERED_BY_QIANKUN__ ? routerBase : '/', mode: 'history', routes: [ { path: '/app1/', component: App, children: [ { path: 'page1', name: 'page1', component: () => import('./views/Page1.vue'), }, { path: 'page2', name: 'page2', component: () => import('./views/Page2.vue'), }, ], }, ], }); instance = new Vue({ router, render: (h) => h(App), }).$mount(container ? container.querySelector('#app') : '#app'); } if (!window.__POWERED_BY_QIANKUN__) { render(); } export async function bootstrap() {} export async function mount(props) { render(props); } export async function unmount() { instance.$destroy(); instance = null; } ``` 在上述代码中,我们在应用中定义了路由规则,并使用 `history` 模式进行路由跳转和页面渲染。在 `render` 函数中,我们使用 `routerBase` 参数来设置应用的前缀,例如 `/app1`,这样就可以在主应用中正确加载应用的路由规则了。 通过以上配置,我们就可以在 Qiankun实现应用内部路由的跳转和页面渲染了。需要注意的是,在实现应用内部路由时,需要确保应用和主应用的路由模式、路由规则等设置一致,以避免出现路由冲突和页面加载错误等问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值