Using multiple widgets in the same page
When using the micro frontend architecture in Modyo, we can use multiple widgets on the same page. We can use them to work together, offering solutions to complex scenarios.
In this example, we will use Vue, but these concepts can be applied to any framework or library. The main issue with tools like Vue, Angular, or React is that they’re designed to be used with single-page applications or in an instance inside an HTML document.
Due to this, in almost every case, you will find an element like this inside the HTML code of applications of this type:
Now that we know the cause, the solution is simple: you have to initialize different values for the IDs and make each Widget unique.
You can accomplish this in two ways: modifying the HTML and JS for each Widget, so they’re unique or using dynamic values and assigning them automatically.
Generate dynamic values for the Widget IDs
To create a dynamic ID in a Vue application in Modyo, first, locate the .env file in your Widget. (If you don’t have this file, follow the instructions in the Creating a widget tutorial in Modyo Docs)
Add a new line with this code:
This will create a variable with the name of the new application. Remember to avoid spaces, special characters, and numbers at the start of the name to avoid compatibility problems with HTML.
Then locate the src/main.js file and replace the value $mount with:
The final step is locating /public/index.html and replacing the value of the current ID with this code:
<div id="<%=VUE_APP_WIDGET_NAME %>"></div>
With these changes, you can compile and upload your widgets so they can work together on a single page. You only have to make sure to assign a unique name to this Widget in the .env file.
Photo by XiaoXiao Sun on Unsplash