Transforming a text into a vNode in VueJS

I recently encountered a situation where I had a string stored in the database that looks something like this:

Lorem #ipsum dolor sit amet, #consectetur adipiscing elit, sed do #eiusmod tempor incididunt ut labore et dolore magna aliqua.

Within the string, you can see that some words are marked with hashtags (#ipsum).

My goal is to display the string within a span, with all the hashtags turned into clickable links.

To accomplish this, I started by using the following code snippet:

let caption = ref(props.caption); // the text mentioned above
const tagRegex = /(#+[a-zA-Z0-9(_)]{1,})/g;

caption.value = caption.value.replace(tagRegex, `<a href="/$1">$1</a>`);

return () => h("span", { "innerHTML": caption.value, class: "text-pre" });

As expected, this code successfully renders the text with clickable links for each hashtag.

The next step involved replacing the a elements with router-link (specifically for Vue Router) and changing the href attribute to to.

However, simply making these replacements did not yield the desired outcome. The router-link elements were rendered in the DOM but were not functioning as intended.

I attempted solutions such as replacing innerHTML with v-html, as well as creating multiple nodes using children, but these approaches did not work either.

If you have any insights or suggestions on how I can achieve the desired result, it would be greatly appreciated. Thank you.

Answer №1

Are you using Vue 3 or Vue 2? I'm leaning towards Vue 3. Here's a neat example of generating router-links dynamically within text.

Check out this Vue 3 Example with dynamic components

You don't have to use a render function for this. You can create components dynamically using the <component> element and providing the is prop. But if you prefer the render function, you can map sections to VNodes using the h function.

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

Error: undefined callback function in asynchronous parallel execution

Encountering the error message "callback is not defined" while attempting to utilize async.parallel has left me puzzled. Most examples of async.parallel demonstrate functions being inline, as shown in the async documentation here: https://caolan.github.io/ ...

Issue with triggering jQuery .submit() function on Bootstrap 3 modal form

I've been attempting to use a Bootstrap 3 modal form to trigger a form.submit() in jQuery, but despite my efforts, I can't seem to get it to work as intended. <div class="modal fade" id="modal-signup" tabindex="-1" role="dialog" aria-labelled ...

JavaScript's onbeforeunload function does not seem to be functioning as intended

I've been encountering issues with implementing onbeforeunload events to alert users when they attempt to navigate away from a page with unsaved form data. Despite creating a basic page, the functionality is inconsistent. There are times when it corre ...

When it comes to HTML and Javascript, there is a distinct contrast between an ajax call and altering the content of an

I am currently working on coding a JavaScript function to allow liking a specific post on Tumblr. I came across this helpful resource for reference. Initially, I attempted using an ajax call instead of modifying the source of an iframe, but unfortunately, ...

Modify a JSON value while iterating through a forEach loop

As I am in the process of setting up an API for my server, I encountered a challenge while attempting to update a value within a JSON structure containing country codes and numerical values. My approach involved iterating through an array of JSON data fetc ...

Blocked: Stripe Connect Embedded Onboarding Popup

I have been diligently following the steps in the tutorial to set up Onboarding with Stripe Connect, which can be found at the following link: After completing all the necessary setup, I encountered an issue where the iFrame containing the "Add Informatio ...

What is the sequence of Javascript Execution for the event of window.location.href?

After browsing through this discussion on asynchronous JavaScript location.href call and watching a video explaining the event loop, I found no clear explanation regarding the behavior of href within window.location: The script order in the source code is ...

Setting up meta tags in React for optimal search engine optimization

In the process of developing a React app with react router, I encountered the need for SEO optimization and adding meta tags to each page. Despite trying out react helmet, it seems that the Yandex micromarkup validator (located at https://webmaster.yandex. ...

Steps for running a function upon activation of a React Router:

I'm currently using Reacter Router to manage the routes of my application. For authentication, I am utilizing an OAuth system that provides my application with the following URL: http://localhost/login-meli?code=1234567890 Every time this particular ...

Resetting ajax success message when modal is closed

Currently utilizing w3.css and its modal feature, I am encountering an issue with clearing the message displayed after a successful ajax call once the window is closed. Even though I have implemented code to clear the message upon closing the window (by cl ...

Refreshing data in Laravel after an AJAX request

Currently, he is working on coding that involves filtering data within a table. Using Ajax to call the link will retrieve a response (json) with the answers. However, there has been an issue. The task at hand is to render tables without using append or sim ...

Creating fresh paths in ReactJS

Is it possible to implement new routes in react JS with the current code provided below? I am looking for a way to create a route that does not need authentication. ReactDOM.render( <Provider store={store}> <PersistGate loading={null} ...

How do I retrieve an index value from an array in GraphQL?

I am seeking a solution for obtaining the index of an array item that is not returned by downstream response. Let's consider my schema: schema: type Cart { items: [Item] } type Item { name: String index: Int } When the data comes in, it lo ...

Removing the day name from an input date in React without relying on Moment.js

I have successfully implemented code to validate dates, but I am unsure how to retrieve the name of the day for a given date input in the field. For instance: if the date input is 12/01/1994, it should display "Wednesday". function isValidDate(inputDate) ...

Want to achieve success with your AJAX calls in JavaScript? Consider using $.get

As I clean up my JavaScript code, I am looking to switch from using $.ajax to $.get with a success function. function getresults(){ var reqid = getUrlVars()["id"]; console.log(reqid); $.ajax({ type: "POST", url: "/api/ser/id/", ...

Guide on encrypting data on the server with PHP and decrypting it on the client side using JavaScript

I'm currently developing a training website with PHP and I am looking to share my training resources securely without worrying about copyright issues. My plan is to encrypt the documents on the server before sending them, and then have them decrypted ...

Maintain vertical spacing within Vue templates using Prettier

I'm currently utilizing the eslint-plugin-vue in my Vue project. In my project, I have a specific configuration defined in the .prettierrc file: // /.prettierrc { "arrowParens": "avoid", "bracketSpacing": true, "insertPragma": false, "jsxBra ...

What could be causing the hover effect to not work on the cards in my Svelte component? (HTML+CSS)

Greetings everyone! This is my debut post on this platform, and I'm in urgent need of assistance as I am relatively new to the world of programming. I've been trying tirelessly to implement a hover effect on these cards, but for some reason, it ...

AngularJS - Refreshing Controller when Route Changes

Scenario app.controller('headerController', ['$scope', '$routeParams', function($scope, $routeParams) { $scope.data = $routeParams; }]); app.config(['$routeProvider', function ($routeProvider) { ...

Updating a select menu with AJAX without the need for a <div> tag within the form

Utilizing an ajax call to dynamically update a select menu is a common practice. The ajax call fetches the options from a separate .php file and populates the select menu accordingly. Below is the code snippet for inserting the dynamic content using JavaS ...