Replacing text dynamically with Vue components

I am currently working on a project where I need to load a text string (https://pastebin.com/Mp9sKy1A) into a webpage and replace instances of --FML-[componentName] with the corresponding component.

For example, --FML-[NoteBlock] should automatically be replaced with the NoteBlock component.

This is my current implementation:

pureContent () {
      const c = this.content.replaced
      const re = new RegExp(`<p>--FML-\\[(\\w+)\\]</p>`, 'g')
      return c.replace(re, ($0, $1) => `<component v-bind:is="${$1.toLowerCase()}"></component>`)
    }

The output will then be inserted into the following template:

<template>
  <div>
    <site-header></site-header>
    <div class="wrapper">
      <side-bar></side-bar>
      <main class="container" v-html="pureContent()" />
    </div>
  </div>
</template>

The current implementation sort of works, but the component part is not being recognized as an actual component. Instead, it displays as a <component> HTML tag, which is not what we want. Is there a way to fix this?

If you are interested, here is the full SFC file: https://pastebin.com/yb4CJ1Ew

This is the current output I am getting:

<main data-v-86dcc3c4="" class="container">
  <h1 id="creating-new-contexts">Creating new contexts</h1>
  <h2 id="section-title">Section Title</h2>
  <h3 id="section-subtitle-that-contains-additional-information">
    Section subtitle that contains additional information
  </h3>
  <p>
    Cillum ipsum ad veniam elit non. Sunt ea ut quis qui dolore id voluptate
    magna. Ex non commodo reprehenderit ipsum irure. Ad excepteur nulla ullamco
    et deserunt magna et sint reprehenderit sint esse commodo. Tempor duis anim
    nisi commodo incididunt ut ex et sunt laborum excepteur ea culpa laborum.
  </p>
  <component v-bind:is="noteblock"></component>
  <p>
    Officia esse Lorem ad duis dolore nostrud ex elit aliqua incididunt sint ad
    ex. Eiusmod do in ad aute nulla eiusmod tempor Lorem non. Qui sunt voluptate
    laborum mollit elit adipisicing minim dolore voluptate veniam incididunt
    proident ullamco. Ipsum est cupidatat occaecat pariatur ut aute.
  </p>
  <component v-bind:is="codeexample"></component>
  <component v-bind:is="propstable"></component>
</main>

The <component> tags should actually render Vue components

Answer №1

It's not possible to achieve this using v-html:

When you update the innerHTML of an element using v-html, keep in mind that the content will be inserted as plain HTML and won't be compiled as Vue templates. If you are finding yourself relying heavily on v-html to compose templates, consider rethinking your approach by leveraging components instead.

You are already working with dynamic components, but what you need is One Component To Rule Them All (and then bind them in the document).

If needed, you can also utilize non-dynamic components internally, especially for defining elements like noteblocks, et. al., as components rather than just data items. However, it is crucial for the container to be a dynamic component so that text data can be transformed into Vue-managed DOM elements.

new Vue({
  el: '#app',
  data: {
    preContent: "<h1 id=\"creating-new-contexts\">Creating new contexts</h1>\n<h2 id=\"section-title\">Section Title</h2>\n<h3 id=\"section-subtitle-that-contains-additional-information\">Section subtitle that contains additional information</h3>\n<p>Cillum ipsum ad veniam elit non. Sunt ea ut quis qui dolore id voluptate magna. Ex non commodo reprehenderit ipsum irure. Ad excepteur nulla ullamco et deserun...
      
        </component>
      });
    }
  }
});
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <component :is="postProcessSpec"></component>
</div>

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

Providing an aggregate outcome from an array

There's a puzzle for you: data = [ '2016-12-12 pass [pass]', '2016-12-12 pass [pass]', '2016-12-12 fail [fail]', '2016-12-13 fail [fail]', '2016-12-14 fail [fail]', '2016-12-14 pass [pa ...

Utilizing jQuery with live content to determine dimensions as required

Within my web application, I have a page that dynamically retrieves a view with both HTML and JavaScript. The JavaScript is responsible for rendering a chart into the retrieved view. The problem arises because the chart library I am utilizing (flot) necess ...

What is the best way to replace an existing item in an array when adding new data?

My goal is to have a single item in an array that gets updated whenever a new item is clicked. Currently, when I click on an item from a list, it is pushed to the array. However, I want the new item to not only be pushed but also overwrite any previous ite ...

Vue.js is utilized in conjunction with Bootstrap 4 for efficient and modern web

I am currently exploring the integration of standard Bootstrap 4 css with a vue.js application. After setting up a basic test project using vue-cli webpack, I included a standard Bootstrap navbar in a header component. Although it displays properly, the li ...

Is there a way to use regular expressions in JavaScript to match tags

As I am not very experienced with regex, my goal is to extract content from the <text> tag and the <music> tag within the given string. The expected result will be two arrays as shown below: The string to match: "<text>Chủ nhật, ng ...

CORS has restricted access to the XMLHttpRequest, despite the backend being configured correctly

I have a Flask backend integrated with React frontend. I encountered an issue while attempting to make a POST request to my backend. The error message states: Access to XMLHttpRequest at 'http://127.0.0.1:5000/predict' from origin 'http://lo ...

Styling with CSS and JavaScript: The ultimate method for desaturating multiple images

I am currently designing a portfolio website that will feature desaturated thumbnails of all my work. When you hover over each thumbnail, the color will fade in and out upon mouseover. Since this page will include numerous thumbnails, I have been contempl ...

How can I use Chart.js to assign a unique color to each x-axis label?

I'm currently using Chart Js to create a chart and I want each label to have a different color instead of all labels having the same color. Is there a way to achieve this using the ticks callback function? scales: { xAxes: [{ ...

Implementing color to text in React JS

Is it possible to change the color of text using inline styles within the HTML tag itself? If so, how can I achieve this? <div id="root"></div><br> <script src="https://unpkg.com/react@16/umd/react.development.js"></script>& ...

Display and conceal panel with the press of the asp:button

Initially, the panel is hidden. I am looking to display the panel when the <asp:button is clicked. Here is my code: <asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="167px" data-ico ...

Sorting data in Javascript can be done efficiently by utilizing the .filter method

Can someone help me identify what I might be doing incorrectly? I have a chained filter under computed that is giving me an error message stating 'product.topic.sort' is not a function. My intention is to use 'select' to provide sortin ...

Is there a way to navigate back to the previous page using an Angular tab within an ASP.NET application?

I am trying to implement a function that will take the user back to the previous page when they click the back button. However, my current code does not seem to be working correctly. Here is the code snippet I have been using: <a href="#" onClick="goBa ...

During an upgrade, IndexedDB replaces existing values

After successfully creating a JSON data set that is passed into IndexedDB during the upgrade event, everything seems to be working fine as it creates a well-structured database without any issues. However, the problem arises when trying to upgrade the data ...

There seems to be an issue with the compilation of TypeScript

I got my hands on the Typescript + AngularJS example downloaded from this source: The issue I'm facing is that whenever I compile it using Visual Studio, the references don't seem to be compiled properly. However, if I utilize the command prompt ...

What is the process for adding and removing classes using CSS's "ClassName" property in React?

I've been diving into React recently and one thing I'm struggling with is how to seamlessly add and remove CSS classes. Take for example the component below: import React from 'react'; import "../../styles/signInAndSignUp.css"; import l ...

The feature to disable swiping with SwipeEnabled set to false seems to be

I am encountering an issue with react-navigation 5 in my react-native project. I am trying to disable drawer swipes while still allowing the user to close the drawer by clicking outside of it. I have researched this property in the react-navigation documen ...

Ways to avoid a child element from overlapping another element

(I acknowledge that the question may sound a bit off, so please feel free to edit it if you can rephrase it better). So, I have this: jsFiddle As you can see, I'm attempting to recreate a basic Windows 7 aero effect (just for curiosity, fun, and lea ...

Issue with Bootstrap 4: Dropdowns not functioning properly

Trying to create a dropdown menu using Bootstrap 4 in my Spring MVC Application, along with Thymeleaf template engine. I've included popper.js and jQuery on my HTML page and also added Bootstrap's CSS and JavaScript files to the static directory. ...

Querying XPATH for an Angular version 10 web application

I have successfully developed a basic web application using Angular 10 for the frontend. Currently, I am working on creating a test script with pytest and Selenium WebDriver. The challenge I'm facing is finding a dependable XPATH to verify the existen ...

What is the process for exporting/importing a variable in Node.js?

What is the correct way to export/import a variable in Node.js? I attempted to use export and import methods, but I received an error message stating that it should be a module. After changing the type to module in the JSON file, it then told me that requ ...