Communication.vue 18.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
<script setup lang="ts">
import type { GlobalState } from '../qiankun';

import { onMounted, onUnmounted, reactive } from 'vue';

import { broadcast, communicationManager } from '../qiankun';

// 全局状态
const state = reactive<GlobalState>({
  user: null,
  theme: {
    mode: 'light',
    primaryColor: '#1890ff',
  },
  notifications: [],
  config: {
    apiBaseUrl: '',
    timeout: 5000,
  },
  currentMenu: null,
});

// 通知表单
const notificationForm = reactive({
  type: 'info' as 'error' | 'info' | 'success' | 'warning',
  title: '',
  message: '',
});

// 配置表单
const configForm = reactive({
  apiBaseUrl: '',
  timeout: 5000,
});

// 颜色选项
const colorOptions = [
  { name: '拂晓蓝', value: '#1890ff' },
  { name: '薄暮', value: '#f5222d' },
  { name: '火山', value: '#fa541c' },
  { name: '日暮', value: '#faad14' },
  { name: '极光绿', value: '#52c41a' },
  { name: '明青', value: '#13c2c2' },
  { name: '极客蓝', value: '#2f54eb' },
  { name: '酱紫', value: '#722ed1' },
];

// 切换用户
const switchUser = (role: string) => {
  const users: Record<
    string,
    {
      avatar: string;
      id: string;
      name: string;
      permissions: string[];
      role: string;
    }
  > = {
    admin: {
      id: '001',
      name: '张三',
      avatar: '👨‍💼',
      role: 'admin',
      permissions: ['read', 'write', 'delete', 'admin'],
    },
    user: {
      id: '002',
      name: '李四',
      avatar: '👤',
      role: 'user',
      permissions: ['read', 'write'],
    },
    guest: {
      id: '003',
      name: '访客',
      avatar: '👥',
      role: 'guest',
      permissions: ['read'],
    },
  };

  const user = users[role];
  communicationManager.updateUser(user);

  broadcast('success', '用户切换', `已切换到: ${user.name} (${user.role})`);
};

// 切换主题模式
const toggleThemeMode = () => {
  const newMode = state.theme.mode === 'light' ? 'dark' : 'light';
  communicationManager.updateTheme({ mode: newMode });

  broadcast(
    'info',
    '主题切换',
    `已切换到${newMode === 'light' ? '浅色' : '深色'}模式`,
  );
};

// 改变主色调
const changeColor = (color: string) => {
  communicationManager.updateTheme({ primaryColor: color });

  broadcast('info', '主题颜色', `主色调已更新为 ${color}`);
};

// 发送通知
const sendNotification = () => {
  if (!notificationForm.title || !notificationForm.message) {
    alert('请填写标题和内容');
    return;
  }

  broadcast(
    notificationForm.type,
    notificationForm.title,
    notificationForm.message,
  );

  // 清空表单
  notificationForm.title = '';
  notificationForm.message = '';
};

// 快速发送通知
const sendQuickNotification = (
  type: 'error' | 'info' | 'success' | 'warning',
) => {
  const messages = {
    success: { title: '操作成功', message: '数据已成功保存到服务器' },
    warning: { title: '警告提示', message: '您的会话即将过期,请注意保存数据' },
    error: { title: '操作失败', message: '网络连接失败,请检查您的网络设置' },
    info: {
      title: '系统提示',
      message: '系统将在今晚23:00进行维护,预计持续1小时',
    },
  };

  const msg = messages[type];
  broadcast(type, msg.title, msg.message);
};

// 更新配置
const updateConfig = () => {
  communicationManager.updateConfig(configForm);
  broadcast('success', '配置更新', '系统配置已更新');
};

// 监听全局状态变化
let unsubscribe: (() => void) | null = null;

onMounted(() => {
  // 初始化状态
  const currentState = communicationManager.getGlobalState();
  Object.assign(state, currentState);

  // 初始化配置表单
  configForm.apiBaseUrl = currentState.config.apiBaseUrl;
  configForm.timeout = currentState.config.timeout;

  // 监听状态变化
  unsubscribe = communicationManager.onStateChange((newState) => {
    Object.assign(state, newState);
  });
});

onUnmounted(() => {
  if (unsubscribe) {
    unsubscribe();
  }
});
</script>

<template>
  <div class="communication-demo">
    <div class="page-header">
      <h1>📡 微前端通信示例</h1>
      <p class="subtitle">演示基座与子应用之间的数据通信</p>
    </div>

    <div class="demo-container">
      <!-- 用户信息管理 -->
      <div class="demo-section">
        <div class="section-header">
          <h2>👤 用户信息管理</h2>
          <span class="tag">全局状态共享</span>
        </div>
        <div class="section-content">
          <div class="current-user">
            <h3>当前用户信息</h3>
            <div v-if="state.user" class="user-display">
              <div class="info-row">
                <span class="label">用户头像:</span>
                <span class="value avatar">{{ state.user.avatar }}</span>
              </div>
              <div class="info-row">
                <span class="label">用户名:</span>
                <span class="value">{{ state.user.name }}</span>
              </div>
              <div class="info-row">
                <span class="label">用户ID:</span>
                <span class="value">{{ state.user.id }}</span>
              </div>
              <div class="info-row">
                <span class="label">角色:</span>
                <span class="value">{{ state.user.role }}</span>
              </div>
              <div class="info-row">
                <span class="label">权限:</span>
                <span class="value">{{
                  state.user.permissions.join(', ')
                }}</span>
              </div>
            </div>
          </div>

          <div class="user-actions">
            <h3>切换用户</h3>
            <div class="button-group">
              <button @click="switchUser('admin')" class="btn btn-primary">
                切换到管理员
              </button>
              <button @click="switchUser('user')" class="btn btn-secondary">
                切换到普通用户
              </button>
              <button @click="switchUser('guest')" class="btn btn-secondary">
                切换到访客
              </button>
            </div>
            <p class="hint">💡 切换用户后,子应用会实时接收到新的用户信息</p>
          </div>
        </div>
      </div>

      <!-- 主题管理 -->
      <div class="demo-section">
        <div class="section-header">
          <h2>🎨 主题管理</h2>
          <span class="tag">全局状态共享</span>
        </div>
        <div class="section-content">
          <div class="theme-display">
            <h3>当前主题</h3>
            <div class="info-row">
              <span class="label">模式:</span>
              <span class="value">{{
                state.theme.mode === 'light' ? '🌞 浅色' : '🌙 深色'
              }}</span>
            </div>
            <div class="info-row">
              <span class="label">主色调:</span>
              <span class="value">
                <span
                  class="color-preview"
                  :style="{ backgroundColor: state.theme.primaryColor }"
                ></span>
                {{ state.theme.primaryColor }}
              </span>
            </div>
          </div>

          <div class="theme-actions">
            <h3>切换主题</h3>
            <div class="button-group">
              <button @click="toggleThemeMode" class="btn btn-primary">
                切换{{ state.theme.mode === 'light' ? '深色' : '浅色' }}模式
              </button>
            </div>
            <div class="color-picker">
              <label>选择主色调:</label>
              <div class="color-options">
                <button
                  v-for="color in colorOptions"
                  :key="color.value"
                  :style="{ backgroundColor: color.value }"
                  class="color-btn"
                  :class="[
                    { active: state.theme.primaryColor === color.value },
                  ]"
                  @click="changeColor(color.value)"
                  :title="color.name"
                ></button>
              </div>
            </div>
            <p class="hint">💡 主题变化会同步到所有子应用</p>
          </div>
        </div>
      </div>

      <!-- 消息通知 -->
      <div class="demo-section">
        <div class="section-header">
          <h2>📢 消息通知</h2>
          <span class="tag">基座向子应用广播</span>
        </div>
        <div class="section-content">
          <div class="notification-form">
            <h3>发送通知</h3>
            <div class="form-group">
              <label>通知类型:</label>
              <select v-model="notificationForm.type" class="form-control">
                <option value="success">✅ 成功</option>
                <option value="warning">⚠️ 警告</option>
                <option value="error">❌ 错误</option>
                <option value="info">ℹ️ 信息</option>
              </select>
            </div>
            <div class="form-group">
              <label>标题:</label>
              <input
                v-model="notificationForm.title"
                type="text"
                class="form-control"
                placeholder="请输入通知标题"
              />
            </div>
            <div class="form-group">
              <label>内容:</label>
              <textarea
                v-model="notificationForm.message"
                class="form-control"
                rows="3"
                placeholder="请输入通知内容"
              ></textarea>
            </div>
            <button @click="sendNotification" class="btn btn-primary btn-block">
              发送通知
            </button>
            <p class="hint">
              💡 发送的通知会显示在右上角的通知中心,所有应用都能看到
            </p>
          </div>

          <div class="quick-actions">
            <h3>快速测试</h3>
            <div class="button-group">
              <button
                @click="sendQuickNotification('success')"
                class="btn btn-success"
              >
                成功消息
              </button>
              <button
                @click="sendQuickNotification('warning')"
                class="btn btn-warning"
              >
                警告消息
              </button>
              <button
                @click="sendQuickNotification('error')"
                class="btn btn-danger"
              >
                错误消息
              </button>
              <button
                @click="sendQuickNotification('info')"
                class="btn btn-info"
              >
                信息消息
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 系统配置 -->
      <div class="demo-section">
        <div class="section-header">
          <h2>⚙️ 系统配置</h2>
          <span class="tag">全局配置共享</span>
        </div>
        <div class="section-content">
          <div class="config-display">
            <h3>当前配置</h3>
            <div class="info-row">
              <span class="label">API 地址:</span>
              <span class="value code">{{ state.config.apiBaseUrl }}</span>
            </div>
            <div class="info-row">
              <span class="label">请求超时:</span>
              <span class="value">{{ state.config.timeout }}ms</span>
            </div>
          </div>

          <div class="config-actions">
            <h3>更新配置</h3>
            <div class="form-group">
              <label>API 地址:</label>
              <input
                v-model="configForm.apiBaseUrl"
                type="text"
                class="form-control"
              />
            </div>
            <div class="form-group">
              <label>请求超时 (ms):</label>
              <input
                v-model.number="configForm.timeout"
                type="number"
                class="form-control"
              />
            </div>
            <button @click="updateConfig" class="btn btn-primary">
              更新配置
            </button>
            <p class="hint">💡 配置更新后,所有子应用都会收到最新配置</p>
          </div>
        </div>
      </div>

      <!-- 通信说明 -->
      <div class="demo-section info-section">
        <div class="section-header">
          <h2>📚 通信方式说明</h2>
        </div>
        <div class="section-content">
          <div class="info-card">
            <h3>1. 全局状态管理 (Global State)</h3>
            <p>
              使用 qiankun 的
              <code>initGlobalState</code> API,实现基座和子应用之间的状态共享。
            </p>
            <ul>
              <li>✅ 双向通信:基座和子应用都可以修改状态</li>
              <li>✅ 实时同步:状态变化会立即通知所有订阅者</li>
              <li>✅ 类型安全:使用 TypeScript 定义状态结构</li>
            </ul>
          </div>

          <div class="info-card">
            <h3>2. Props 传递</h3>
            <p>基座在注册子应用时,可以通过 props 向子应用传递数据。</p>
            <ul>
              <li>✅ 单向数据流:基座向子应用传递</li>
              <li>✅ 配置传递:适合传递路由配置、权限等静态数据</li>
              <li>✅ 生命周期传递:在 mount、update 时传递</li>
            </ul>
          </div>

          <div class="info-card">
            <h3>3. Actions 通信</h3>
            <p>通过全局状态管理器,实现消息通知、事件广播等功能。</p>
            <ul>
              <li>✅ 事件驱动:基于发布订阅模式</li>
              <li>✅ 广播消息:一对多通信</li>
              <li>✅ 解耦合:应用之间不直接依赖</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.communication-demo {
  max-width: 1400px;
  padding: 24px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 32px;
}

.page-header h1 {
  margin-bottom: 8px;
  font-size: 32px;
  color: #262626;
}

.subtitle {
  margin: 0;
  font-size: 16px;
  color: #8c8c8c;
}

.demo-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.demo-section {
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 8%);
}

.section-header {
  display: flex;
  gap: 12px;
  align-items: center;
  padding-bottom: 16px;
  margin-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;
}

.section-header h2 {
  margin: 0;
  font-size: 20px;
  color: #262626;
}

.tag {
  padding: 4px 12px;
  font-size: 12px;
  font-weight: 500;
  color: white;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
}

.section-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.current-user,
.user-actions,
.theme-display,
.theme-actions,
.notification-form,
.quick-actions,
.config-display,
.config-actions {
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
}

h3 {
  margin: 0 0 16px;
  font-size: 16px;
  color: #262626;
}

.info-row {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 12px;
}

.info-row .label {
  min-width: 80px;
  font-weight: 500;
  color: #595959;
}

.info-row .value {
  color: #262626;
}

.info-row .value.avatar {
  font-size: 24px;
}

.info-row .value.code {
  padding: 2px 8px;
  font-family: Consolas, Monaco, monospace;
  font-size: 13px;
  background: #f5f5f5;
  border-radius: 4px;
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
}

.btn {
  padding: 8px 16px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  border: none;
  border-radius: 6px;
  transition: all 0.2s;
}

.btn:hover {
  box-shadow: 0 4px 12px rgb(0 0 0 / 15%);
  transform: translateY(-2px);
}

.btn-primary {
  color: white;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.btn-secondary {
  color: #262626;
  background: #f0f0f0;
}

.btn-success {
  color: white;
  background: #52c41a;
}

.btn-warning {
  color: white;
  background: #faad14;
}

.btn-danger {
  color: white;
  background: #ff4d4f;
}

.btn-info {
  color: white;
  background: #1890ff;
}

.btn-block {
  width: 100%;
}

.hint {
  padding: 12px;
  margin: 12px 0 0;
  font-size: 14px;
  color: #0050b3;
  background: #e6f7ff;
  border-left: 3px solid #1890ff;
  border-radius: 4px;
}

.color-picker {
  margin-bottom: 16px;
}

.color-picker label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #595959;
}

.color-options {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.color-btn {
  width: 40px;
  height: 40px;
  cursor: pointer;
  border: 3px solid transparent;
  border-radius: 8px;
  transition: all 0.2s;
}

.color-btn:hover {
  transform: scale(1.1);
}

.color-btn.active {
  border-color: #262626;
  box-shadow: 0 0 0 2px white;
}

.color-preview {
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 8px;
  vertical-align: middle;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #595959;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  font-size: 14px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  transition: all 0.2s;
}

.form-control:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgb(24 144 255 / 10%);
}

textarea.form-control {
  font-family: inherit;
  resize: vertical;
}

.info-section .section-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-card {
  padding: 20px;
  background: linear-gradient(135deg, #667eea11 0%, #764ba211 100%);
  border-left: 4px solid #667eea;
  border-radius: 8px;
}

.info-card h3 {
  margin-bottom: 12px;
  color: #262626;
}

.info-card p {
  margin-bottom: 12px;
  line-height: 1.6;
  color: #595959;
}

.info-card code {
  padding: 2px 6px;
  font-family: Consolas, Monaco, monospace;
  font-size: 13px;
  color: #d63200;
  background: #f5f5f5;
  border-radius: 4px;
}

.info-card ul {
  padding-left: 20px;
  margin: 0;
}

.info-card li {
  line-height: 1.8;
  color: #595959;
}

@media (max-width: 1024px) {
  .section-content {
    grid-template-columns: 1fr;
  }
}
</style>