2

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?

1 Answer 1

4

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)
  },
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.