Transform HTML into a Vue component dynamically during runtime

Currently, I am in the process of learning Vue and working on a simple wiki page project. The raw article data is stored in a JSON file written using custom markup. For example, the following markup: The ''sun'' is {r=black black} should be translated as follows:

<p>The <b>sun</b> is <Ref path="/black">black</p>
I have managed to achieve this using regular expressions and string manipulation techniques. However, I cannot use this processed string as a template option because it only works with static inputs. If it were pure HTML, I could have utilized the v-html directive or similar methods. My current template fetches the JSON file and interprets my custom markup based on preset criteria. It then generates a string containing Vue markup, which unfortunately cannot be assigned to the 'template' options due to its restriction to static strings and inability to recognize variables.

I attempted assigning the template options with a pre-compiled Vue markup or utilizing a runtime compiler mechanism. Yet, I may be misunderstanding something. Any suggestions on how I can proceed?

Answer №1

To compile a Vue template, use the compile() function and insert it into your current template using <Component>. Additionally, remember to update the alias import from 'vue' to 'vue/dist/vue.esm-bundler.js' in vite.config.js to enable this functionality.

https://i.stack.imgur.com/jbjUw.png

Modified files after running npm create vue@latest:

App.vue

<script setup>

import { ref, compile } from 'vue';

const msg = ref('Hello world!');
const component = ref(compile('<HelloWorld :msg="msg"></HelloWorld>'));

</script>

<template>
    <main>
        <Component :is="component" :msg="msg"></Component>
    </main>
</template>

main.js

import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'


const app = createApp(App);
import HelloWorld from './components/HelloWorld.vue'
app.component('HelloWorld', HelloWorld);
app.mount('#app')

vite.config.js

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        vue(),
    ],
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url)),
            vue: 'vue/dist/vue.esm-bundler.js',
        }
    }
})

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

Meteor - An error occurred in the Subscription Publish Function because it returned an array of non-Cursors

I'm attempting to publish a collection, but my console is showing that it returns an array. server/publish.js HeartCount = new Mongo.Collection('heartcount'); Meteor.publish("currentHeartCount", function() { return HeartCount.find().f ...

CSRF Token currently disabled

I am working on creating a VueJs Form to be included in a php.blade file where users can leave comments and rate between 0 and 5 stars. The challenge I am facing is the possibility of a CSRF attack, even though I have implemented a CSRF token in my form. ...

Resolving issues with setting up d3.js in the 'Creating a Custom Map' guide

Starting Mike Bostock's tutorial on creating a map, but facing some installation issues at the beginning. I am using Windows 8.1 for this. This is the specific part that's causing trouble: "To get started, you'll need the reference implemen ...

Converting an Array with Key-Value pairs to a JSON object using JavaScript

After using JSON.stringify() on an array in JavaScript, the resulting data appears as follows: [ { "typeOfLoan":"Home" }, { "typeOfResidency":"Primary" }, { "downPayment":"5%" }, { "stage":"Just Looki ...

AngularJS filtering with multiple conditions

My ng-repeat list is currently displaying a collection of objects with a filter applied to only show objects inserted today. Here is how it looks: <div class="row msf-row" ng-repeat="record in recordlist | filter: record.date = dateJson"> Whi ...

Show Pop in relation to modified Text

When the user clicks on the text, a pop-up is displayed after the last word in the text.... https://i.stack.imgur.com/VWQCa.png The logic being used is : left = layer.width + layer.x Code : document.getElementById(lightId).style.left = layer.x + docume ...

By setting `queue: false` when calling jQuery's `show()` method, you can

When looking at the code below, it is clear that even though showLoader is the first call, the loader does not appear immediately. This delay is due to the fact that heavyLifting function is blocking the UI thread. function onClick() { showLoader(); ...

Inquiring about socket.io: How can an io emit its own signal?

I am currently working on implementing the emit event in an express router, and I'm attempting to pass a global.io variable. However, I've encountered an issue where despite adding the following code: io.emit('join','Tudis' ...

The challenge of loading multiple objects asynchronously in three.js

When I try to load multiple models onto the same scene simultaneously, only one model is successfully loaded. For instance, if I have a building scene with various objects like chairs and toys inside, only one object gets loaded when I try to load them all ...

Utilizing Visual Studio: Implementing jsmin in post-build actions

After attempting to add jsmin.exe as a post-build event in my VS 2010 project, I encountered an "error code 9009" when building the project. I tested this in the command prompt and found that it works if I navigate to the folder and run: jsmin < debug ...

Experiencing troubles when trying to execute npm run serve with vue/cli

I started a project with the following commands: vue create test After navigating to my repository: cd test When I tried to launch it using: npm run serve I encountered an issue: INFO Starting development server... ERROR Error: No valid exports m ...

Should I fork and customize npm package: Source or Distribution? How to handle the distribution files?

Currently, I am in the process of developing a VueJS web application. Within this project, there is a module that utilizes a wrapper for a JavaScript library obtained through npm and designed to seamlessly integrate with VueJS. However, it doesn't com ...

Tips for accessing hidden field values in a second jsp page

I have a webpage called page1.jsp where I am including hidden fields. Here is the code snippet: <form action = "page2.jsp" method = "post" id = "hiddenValuesForm"> <input type = "hidden" name = "userData" value="" id = "useDataID"> <input t ...

Utilize Express Node to display API information on HTML pages using Handlebars template

I'm seeking assistance in rendering data from an API to HTML using handlebars. I'm a bit puzzled on how to properly showcase the data on the webpage. Here's what I have so far: ROUTES FOLDER/FILE: const express = require('express&ap ...

Tracking dynamic collections in AngularJS ng-repeat using track by

I am attempting to utilize ng-repeat with the result of a function call, like this: <body ng-init='a = [1, 2, 3]'> <div ng-repeat='item in f(a) track by item[0]'>{{item}}</div> </body> where the function f is ...

Creating an object property conditionally in a single line: A quick guide

Is there a more efficient way to conditionally create a property on an object without having to repeat the process for every different property? I want to ensure that the property does not exist at all if it has no value, rather than just being null. Thi ...

Concealing items by placing them strategically between the camera and certain objects in Three.js

At the moment, my project involves utilizing three.js with several objects in the scene. One of the key features I am working on is the ability to select an object and have all other objects between the camera and the selected one hidden or removed. I am ...

Step-by-step guide on dynamically adding "Input Tags" to the DOM at runtime using Selenium's JavascriptExecutor

In order to dynamically add the following element to the DOM during run time, I need assistance... <input type="text" name="imagesToAdd" value="3566"> My initial attempt was to use Selenium JavascriptExecutor for this task. However, I encounter ...

Ways to detect when the window printing process has been completed

Within my application, I attempted to generate a voucher page for the user using the following code: var htm ="<div>Voucher Details</div>"; $('#divprint').html(htm); window.setTimeout('window.print()',2000); The &apo ...

When attempting to set the keyPath using a variable, an error occurs stating that the keyPath option is not a valid key path

My JSON object, stored in a variable named "jsonObjSuper", is structured like this: { "Watchlist": "My Watchlist", "Instruments": { "instrument1": [ "Company ABC", [ { "snapshotTimeUTC": "2018-11-01T00:00:00", "snapshotTime": "2018/11/ ...