简体   繁体   中英

How to render Vue Component dynamically with render()

In Vuejs 3 I want to use the render() function to create a VNode, passing it a Vue Component . This component varies depending on the current route.

In vite.js I haven't found a way to import a component dynamically inside my ViewComponent computed function.

With webpack I could normally use return require(`./pages/${matchingPage}.vue`).default , but this is not possible with vitejs as I will get a Require is not a function error.

So I tried return import(`./pages/${matchingPage}.vue`) but it returns a Promise , not a 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')

What other ways can I try so render() can return a Component dynamically?

You could use 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)
  },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM