Converting string components into actual components in Vue: A step-by-step guide

I have a specific need for a plugin store where I want to load a component from the core into plugins and then convert that string into an actual component within the plugin for usage.

Please suggest better approaches for implementing the plugin store within the core.

Here is my approach:

  1. Retrieve the component from a specified path using http
  2. Convert the loaded string into a real Vue component and store it in a variable
  3. Render the component in the DOM
let componentAsString = 

`<template>
  <div>
      <h class="red">{{title}}</h>
      <!--<A></A> -->
  </div>
</template>

<script>
//import A from './components/A'

export default {
  name: 'App',
  data(){
      return {
        title:'Hello World'
      }
  },
  /*components: {
    A
  }*/
}
</script>

<style lang="scss" scoped>
   .red{color:red;}
</style>`;

Answer №1

You have opted for a challenging approach in solving the requirement. The main issue lies in the content of the string, which is essentially a Vue SFC (.vue file). Converting this SFC into a usable Vue component in the browser requires several steps. You need to utilize tools like Webpack (or Rollup), integrate vue-loader for parsing the SFC, and apply different Webpack loaders to handle each section of the SFC (such as Babel for transpiling the <scipt> block, sass-loader and sass compiler for converting

<style lang="scss">
into CSS)

While there are browser-based tools available for some of these tasks (like vue3-sfc-loader), they come with significant drawbacks - for instance, vue3-sfc-loader adds approximately 1.4MB of minified JavaScript to your project. This additional weight can impact performance significantly.

An easier alternative is to leverage standard tooling at build time

  1. Create your components as usual, within .vue files
  2. Utilize your components as Async Components and compile a list of available components. These components will be built into separate JavaScript files during compilation and loaded on-demand in the browser
// ComponentStore.js
export default {
  component1: () => import('./components/component1'),
  component2: () => import('./components/component2'),
}

Note: Automation tools can streamline the process of creating this component dictionary. For example, check out this reference

  1. Implement the component as a dynamic component
// DynamicComponent.vue
<template>
  <component :is="comp" />
</template>
<script>
import ComponentStore from "ComponentStore.js"

export default {
  props: ['componentName'],
  computed: {
    comp() {
      return ComponentStore[this.componentName]
    }
  }
}
</script>

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

Why is Visual Studio Code not highlighting my nested multi-line JavaScript comment as I anticipated?

/*/*! what is the reason */ for this annotation*/ Can someone explain why the annotation is not working as expected in this scenario? I've already verified it in VS code. ...

Updating the URL in React and Redux

I am currently working on developing an application using React and Redux (DVA) with Ant.Design as the main framework. I am facing an issue where I need to change the URL when a user clicks on a button, and connect that URL change to a specific action so t ...

The initial rendering of the connected component is unsuccessful due to the fact that the Redux state has not been fully

Currently, I am utilizing Redux thunk and axios to handle server requests and update the state based on the response. An issue arises when trying to render a connected component with an initial state that relies on data from the server. In this scenario, ...

Delete any HTML content dynamically appended by AJAX requests

I'm currently working on a page dedicated to building orders, where the functionality is fully dependent on ajax for finding products and adding them dynamically. However, I encountered an issue when attempting to remove an item that was added via aj ...

Creating JavaScript Objects from HTML Form data with the help of serializeJSON

Struggling extracting HTML form data into the required JSON format for server communication. Despite following a guide, I can't get the output right. Managed to extract question keys and values, but labeling is tricky. Current Output: {"Question1":" ...

Finding the Client's Private IP Address in React or Node.js: A Comprehensive Guide

Issue I am currently facing the challenge of comparing the user's private IP with the certificate's IP. Is there a method available to retrieve the user's private IP in react or node? Attempted Solution After attempting to find the user&a ...

Issues have been encountered with the functionality of $rootScope

I am currently struggling with a code snippet in my loginCtrl.js file where I can't seem to get $rootScope to store the value of vm.userEmail. app.controller('LoginCtrl', function($timeout, $q, $log, $rootScope /*$auth*/, $location, $mdTo ...

Simulating NextJS router triggers using Jest

I've been attempting to simulate NextJS router events using Jest. I came across a useful resource at NextJS router & Jest. The approach outlined there closely resembles mine. Unfortunately, the solution provided in that post is not yielding the d ...

Uppercase the initial letter in a term to indicate a standard condition

I'm struggling to override the CSS in material UI. Even though I tried capitalizing both words, it only changes on selected and hover states, Is there a way to change it in the normal state as well? I've tried debugging but can't seem to fin ...

How can I make Material UI's grid spacing function properly in React?

I've been utilizing Material UI's Grid for my layout design. While the columns and rows are functioning properly, I've encountered an issue with the spacing attribute not working as expected. To import Grid, I have used the following code: ...

Triggering the Vuetify select/autocomplete/combobox menu to open upon focusing on it

I'm working on implementing a Vuetifyjs Autocomplete feature. My goal is to have the menu open when the user focuses on it using the tab key after entering information in a previous input field. Below is a snippet of the code I am using: <div id=" ...

What is the most effective method for displaying formatted text from SQL on a client?

How can I effectively display formatted text stored in SQL that originated from Google Docs and PDF documents? I've received two suggestions thus far: Simply copy and paste the text into <pre></pre> tags, but this solution seems limited ...

When the web driver fails to function as expected

After installing the selenium-webdriver via npm, I downloaded the IE component from this link and added it to my path on Windows 8. Upon opening IE, I had to set all security zones to high, ensuring they were consistent. However, due to restrictions in th ...

Viewing multiple pages and maintaining sessions in Laravel

I am currently working on a quiz application that involves multiple pages depending on the user's selection. However, I have encountered an issue with Laravel's pagination not saving previous page inputs. Is there a way to resolve this problem? A ...

React Dilemma: Moving from Controlled to Uncontrolled Component

I am currently working on a FORM that should store the values in state upon submission. However, I'm encountering an issue while trying to achieve this. The problem is that I am only able to retrieve the value of the last input in my formcontrol, wh ...

Modify the button's border color upon click action

I am looking to implement a feature where the border of a button changes when clicked once and reverts back when clicked again. This should apply individually to each of the 16 buttons with the same class. Additionally, I want to enable the ability to clic ...

Steps to update the active state in the "reducer" when clicking on elements outside of the "reducer" area

Working with react-redux has presented some challenges for me. I've created multiple reducers such as action, root reducer, active_step reducer, and list_step reducer. One aspect that I find intriguing is the ability to dynamically map and change the ...

What is the rationale behind TypeScript's decision to permit omission of "this" in a method?

The TypeScript code below compiles without errors: class Something { name: string; constructor() { name = "test"; } } Although this code compiles successfully, it mistakenly assumes that the `name` variable exists. However, when co ...

Troubleshooting the malfunction of the CSS display property

I've created a div with a number displayed initially. When I hover over the div, the number disappears and a paragraph is revealed. Upon hovering out, the paragraph hides and the number reappears. My attempts to achieve this using CSS (display: none ...

html5sql - Struggling to establish a connection with my database

I recently started using html5sql.com for my html5 DB needs and I must say, it's a fantastic module! However, I've hit a roadblock. In my index.html/index.js file, I have set up my database and created tables in it. try { html5sql.open ...