如何使用 render() 动态渲染 Vue 组件

How to render Vue Component dynamically with render()

Vuejs 3 中,我想使用 render() 函数创建一个 VNode,将其传递给 Vue Component。此组件因当前路线而异。

vite.js 中,我还没有找到在我的 ViewComponent 计算函数中动态导入组件的方法。

使用 webpack 我通常可以使用 return require(`./pages/${matchingPage}.vue`).default,但是使用 vitejs 是不可能的,因为我会得到一个 Require is not a function 错误。

所以我尝试了 return import(`./pages/${matchingPage}.vue`) 但它 return 是 Promise,而不是 Component

//main.js

import {createApp, h} from 'vue'
import routes from './routes'

const SimpleRouterApp = {
  data: () => ({
    currentRoute: window.location.pathname
  }),

  computed: {
    ViewComponent () {
      const matchingPage = routes[this.currentRoute] || '404'
      return import(`./pages/${matchingPage}.vue`)
    }
  },

  render () {
    return h(this.ViewComponent)
  },

  created () {
    window.addEventListener('popstate', () => {
      this.currentRoute = window.location.pathname
    })
  }
}

createApp(SimpleRouterApp).mount('#app')

我可以尝试哪些其他方法,以便 render() 可以 return 动态地 Component

你可以使用 async-components :

import {createApp, h,defineAsyncComponent} from 'vue'
....
  

  render () {
  const matchingPage = routes[this.currentRoute] || '404'
    const ViewComponent= defineAsyncComponent(
      () =>import(`./pages/${matchingPage}.vue`)
   
   )
    return h(ViewComponent)
  },