index.vue 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <template>
  2. <component :is="currentComponent" />
  3. </template>
  4. <script>
  5. import { ref, computed } from 'vue'
  6. import { mapState } from 'pinia'
  7. import useUserStore from '@/store/modules/user'
  8. import { getRouteNameByPostType } from '@/utils/routeMap'
  9. import { getCurrentUserHomePage } from '@/api/system/postHomePage'
  10. import Index0 from './index0.vue'
  11. import Index1 from './index1.vue'
  12. import Index2 from './index2.vue'
  13. export default {
  14. name: 'Index',
  15. components: {
  16. Index0,
  17. Index1,
  18. Index2
  19. },
  20. setup() {
  21. const homePageRouteName = ref('')
  22. // 根据路由名称确定要加载的组件
  23. const currentComponent = computed(() => {
  24. // 直接使用homePageRouteName值作为组件名称,提高代码简洁性
  25. // 由于组件已注册,Vue会自动解析组件名称
  26. return homePageRouteName.value || 'Index0'
  27. })
  28. // 获取首页路由名称
  29. const fetchHomePageRouteName = async () => {
  30. try {
  31. // 调用后端接口获取首页配置
  32. const response = await getCurrentUserHomePage()
  33. console.log(response);
  34. if (response.code === 200 && response.data) {
  35. // 使用返回数据中的homePageType值
  36. const homePageType = response.data.homePageType
  37. homePageRouteName.value = await getRouteNameByPostType(homePageType)
  38. } else {
  39. // 接口调用成功但无数据时使用默认首页
  40. console.warn('未获取到首页配置数据,使用默认首页')
  41. homePageRouteName.value = 'Index0'
  42. }
  43. } catch (error) {
  44. console.error('获取首页配置失败:', error)
  45. // 接口调用失败时使用默认首页
  46. homePageRouteName.value = 'Index0'
  47. }
  48. }
  49. console.log(homePageRouteName.value);
  50. return {
  51. homePageRouteName,
  52. currentComponent,
  53. fetchHomePageRouteName
  54. }
  55. },
  56. computed: {
  57. ...mapState(useUserStore, ['postType'])
  58. },
  59. async mounted() {
  60. // 组件挂载时获取首页路由名称
  61. if (this.fetchHomePageRouteName) {
  62. this.fetchHomePageRouteName()
  63. }
  64. },
  65. watch: {
  66. // 监听postType变化
  67. postType: {
  68. handler: async function(newVal) {
  69. if (this.fetchHomePageRouteName) {
  70. this.fetchHomePageRouteName()
  71. }
  72. },
  73. immediate: true
  74. }
  75. }
  76. }
  77. </script>