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

The slider thumb is not showing up properly on Microsoft Edge

Hey there! I'm experiencing an issue with the range slider's thumb display in Microsoft Edge. It appears to be positioned inside the track rather than outside as intended. Take a look at this snapshot for clarification: https://i.stack.imgur.co ...

Simple solution for storing key-value pairs temporarily in a form using JQuery

Is there an elegant method to temporarily store an array of string values in a form? In my article editing form, users can add tags as string values. I don't want these tags to be persisted until the user saves the entire article, so I require a way ...

Placing the video at the center of the background image

                    Can someone assist me with a design issue I'm facing? I have two divs within a section. The left div contains a heading and a button, while the right div contains a video. However, when I try to add a background image to ...

Combining strings with JQuery

Looking for help with a code snippet <script> function goToDetails($i){ $(function(){ var transValue = $('#trans'+$i).html(); var mileageValue = $('#mileage'+$i).html(); var engineValue = $('#eng'+$i).html ...

Showing how to make an element visible in Selenium and Python for file uploading

Check out this HTML snippet: <div class="ia-ControlledFilePicker"><input class="ia-ControlledFilePicker-control icl-u-visuallyHidden" type="file" id="ia-FilePicker"><label class="ia-ControlledFilePicker-fakeControl" for="ia-FilePicker">C ...

Managing business logic in an observable callback in Angular with TypeScript - what's the best approach?

Attempting to fetch data and perform a task upon success using an Angular HttpClient call has led me to the following scenario: return this.http.post('api/my-route', model).subscribe( data => ( this.data = data; ...

Automatically selecting the map center while using the Drawing Manager feature for placing markers

My application utilizes the Google Drawing Library. When a user clicks on the Add New Marker Button, the Drawing Manager is activated allowing the user to generate a marker by clicking anywhere on the map. Subsequently, the following listener is executed: ...

Brand new Laravel 9 setup featuring a vue 3 scaffold, but encountering issues with vite not displaying components

After setting up a fresh Laravel 9.19 installation with Vue scaffolding and vite.js, everything seemed to be working well, except for one issue - the Vue example component that comes with the default Laravel install wasn't rendering in the browser. M ...

Attempting to incorporate country flags into the Currency Converter feature

www.womenpalace.com hello :) i'm looking to customize my Currency Converter with Flags images. this is the code for the converter: <select id ="currencies" class="currencies" name="currencies" data-default-shop-currency="{{ shop.currency }}" ...

Tips for ensuring the validity of data in an AJAX request

When trying to fetch data using the REST method, I utilize an AJAX call. While my work is completed, I encounter an issue with validating the "data" within the AJAX call. How can I accomplish this? If there is no data returned from the specified URL, it ...

Exploring the Significance of jQuery in a Real-

I manage a large website with an extensive amount of jQuery code spread across multiple pages. The total codebase is around 1000 lines, well-optimized and excluding plugins. Despite jQuery being efficient in ignoring listeners for non-existent page elemen ...

Hiding the modal once the data has been successfully transmitted to the database

I am facing a challenge in my app where I need to close the modal after sending data to the database, but no matter what I try, I cannot seem to achieve it. Can anyone provide some guidance or assistance with this? :) <div class="container-fluid"&g ...

Error with Expression Engine: PHP function cannot be executed

I have been attempting to execute a PHP Script with ExpressionEngine tags using Ajax on my webpage. I followed the documentation and set up the PHP script accordingly, but it appears that I am unable to call the function in the PHP script. There must be so ...

Tips for designing a sophisticated "tag addition" feature

Currently, I am enhancing my website's news system and want to incorporate tags. My goal is to allow users to submit tags that will be added to an array (hidden field) within the form. I aim to add tags individually so they can all be included in the ...

Exploring the Live Search Functionality on an HTML Webpage

I am attempting to create a live search on dive elements within an HTML document. var val; $(document).ready(function() { $('#search').keyup(function() { var value = document.getElementById('search').value; val = $.trim(val ...

Pass along a variable with either "&" or "%" to a PHP file utilizing JavaScript

I have a JavaScript script that is sending 4 variables to a PHP page. The issue arises when one or more of these variables contain special characters like "&" or "%". The script ends up only sending the content before those characters. For example, if ...

Utilizing CSS classes based on subelements

I need to assign css classes to items in a list based on certain criteria. Here is an example of the structure I am working with: <ul ng-controller="Navigation"> <li><a href="#">Category A</a> <ul> < ...

Ways to retrieve the value of a specific key within an object nested within another object

Suppose I have a variable named x with the following structure: x = { choice1: { choice: { name: "choice1", text: "abc", key: "key1" } isChecked: true }, choice2: { choice: { name ...

Learn how to manipulate Lit-Element TypeScript property decorators by extracting values from index.html custom elements

I've been having some trouble trying to override a predefined property in lit-element. Using Typescript, I set the value of the property using a decorator in the custom element, but when I attempt to override it by setting a different attribute in the ...

Creating images with LibCanvas

Currently, I am utilizing LibCanvas for canvas drawing on my HTML page. However, I am facing difficulty in drawing an image. Can someone provide assistance with this? UPDATE: The code snippet I am using is showing the image being drawn but then it disappe ...