Tips for dynamically rendering Vue components using the render() method

When working with Vuejs 3, I am interested in using the render() function to generate a VNode, where I can pass a Vue Component that changes based on the current route.

In my use of vite.js, I have encountered difficulty importing a component dynamically within my computed function for ViewComponent.

Previously, in webpack, I could easily achieve this with

return require(`./pages/${matchingPage}.vue`).default
. However, due to restrictions in vitejs, utilizing this method results in a Require is not a function error.

I experimented with

return import(`./pages/${matchingPage}.vue`)
, but this approach returns a Promise instead of a direct 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')

I am seeking alternative methods to enable render() to dynamically return a Vue Component. Any suggestions?

Answer №1

If you want to dynamically load components, consider using 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);
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the magic of Hover effects using CSS and JQuery

I am exploring ways to enhance the display of an element when hovering over it. I have implemented a button and my objective is for the first click to activate the hover effect, while the second click will reset it. However, I am facing an issue where the ...

Can we convert a PHP frontend into a Vue node?

I'm currently working on transitioning a legacy PHP application to Vue, and I want to do it gradually. The current PHP app is quite messy, with HTML and JavaScript files intertwined in a complicated manner like this: foo.js.php ... <script src=&quo ...

Receiving an error of "undefined" when trying to capture the selected

One issue I am facing is capturing the selected user option and sending that value in a post request. Let's put aside the post part since it's not directly related to the main question at hand. Currently, the value is showing up as undefined. ...

The validation directive is run on each individual item within the ng-repeat loop

As I develop a single page application utilizing Angular and Breeze, the challenge of managing entities with dynamic validation arises. With a set of entities displayed on the page using data-ng-repeat, I implement in place validation through toggling betw ...

AngularJS, perform an action on an HTML element within an ng-repeat directive once the user interface has been rendered

When using AngularJS to add a row to an HTML table by clicking an "Add row" button and using $scope.photos.push({}), you may encounter an issue when trying to trigger the file dialog of the new row's file input field. Is it possible to do this and if ...

Storing executable scripts in HTML5 LocalStorage allows for the dynamic creation

As I work on a hybrid app with its own local HTML and JS files, there are times when I need to load additional small executable JS scripts and CSS from the server. Currently, I achieve this by using $.getScript, which has been working well. In order to ma ...

Is the XPath in Selenium executed against the Document Object Model (DOM) or the HTML file

Currently, I am in the process of developing a library for analyzing webpages. My approach involves using Selenium to access elements on a webpage through xpath. I have been contemplating replacing Selenium with an offline xpath tool. However, upon furthe ...

Get the value of an HTML element

Is there a way to retrieve the value of an HTML element using PHP or JavaScript, especially when the value is dynamically loaded from another source? I have tried using jQuery with the DOM ready event, but often encounter the issue where the element's ...

Tips for generating JSON data in the correct format dynamically while continuously adding new information to the existing object

In my form, users input their email and password, which then generates dynamic JSON upon submission. However, I encountered an issue where the JSON gets corrupted when logging in with different user details as it updates the existing JSON with a new object ...

Can the Browser width/document width be maintained when shrinking the browser window size?

https://i.stack.imgur.com/a4gfA.pngLooking for a solution to maintain the browser/document width at 350px, preventing users from minimizing the window. The desired width is actually 400px, not 350px. Please refer to the image above. I require the window ...

Is it possible to customize the appearance of the <audio> tag when used with a playlist?

I am struggling to style an audio tag with a playlist of songs. Does anyone have any pre-made styles that I can use for a normal white MP3 player similar to the one in the picture I attached? The MP3 player I'm aiming for Current player design Her ...

Initiate a function once the innerHTML content in Angular has been completely loaded

I'm curious to know if it's possible in Angular to receive a notification when the Inner HTML has finished loading. I have a web application that retrieves an SVG image from a server and I need to display it as innerHTML in order to interact with ...

Conceal the element at all times

I'm facing a challenge with a paragraph element that is dynamically filled with content using Javascript. I need to hide the element whenever it doesn't have any text within it. However, I want to avoid using setTimeout or setInterval for this ta ...

Solved error message: "The method ResponseFactory::toArray is not available."

In my current setup with Laravel 7.6 and Vue 2, I am facing an issue with converting a Laravel collection to an array. The original code that is working fine is as follows: public function index() { $books = Book::all()->toArray(); return array ...

Having trouble accessing undefined properties in ReactJs? Specifically, encountering issues when trying to read the property "name"?

I am facing an issue with using the data in my console even though I can log it. The structure of my data object is as follows: {_id: '616bf82d16a2951e53f10da4', name: 'abd', email: '[email protected]', phone: '123456789 ...

Removing specific elements from an array with repetitive items can be tricky, especially when using Lodash or Underscore. Here's a guide on how to

Is there a simple way to use Lodash or Underscore to filter out triplets from an array of 6 dice? noTriplets([1,1,1,3,3,5]) // = [3,3,5] noTriplets([1,1,1,1,3,5]) // = [1,3,5] noTriplets([1,1,1,1,1,5]) // = [1,1,5] noTriplets([1,1,1,5,5,5]) // = [] noTr ...

Integrating Watson Conversation with Oracle Database

Hello everyone, I am currently working on a project where I need Watson to fetch a response manually set from our Oracle Databases. To achieve this, I am using async to access the database sequentially and return the response. Initially, I faced an issue ...

Retrieve the state data from the store and convert it into a string using Vue.js

Dear friends, I need some help with incorporating state data from my Vuex store into a string in one of the axios calls within actions. Below is an excerpt from my store: export const store = new Vuex.Store ({ state: { participants: [], filterTa ...

How can I utilize Django Rest Framework to send and retrieve an xlsx file?

I've been facing a challenge for quite some time now when it comes to sending a file to the client-side using django-rest-framework. I've managed to send it as a byte, but I'm struggling to handle it on the client-side for downloading it as ...

Unable to get windw.location.href to function properly on local server

Having trouble with window.location.href not working for me :/ Everything is running on a localhost using "xampp" //javascript function 1 function onLogin() { window.location = "http://localhost:4000/deletetable"; console.log("running..."); con ...