This content originally appeared on Level Up Coding - Medium and was authored by Marius D

When using v-html (for example to display an article pulled from your CMS) it is desirable replace local links with Vue Router’s <router-link> to ensure that your app does not unnecessarily reload when a user clicks the link.
This example uses a standalone Component to encapsulate our functionality:
Injection happens in Component’s mounted() callback. First we need the DOM Element which contains our dynamic content. In our case it is directly: this.$el . Now retrieve all anchors inside dynamic content: this.$el.getElementsByTagName('a')
Iterate each Element and drop links which lead to external sites.
Vue Router docs do not indicate whether we can use the beginning of the URL (https://example.com) so we just remove it to obtain the path. Obtain a constructor for <router-link> and instantiate it by passing the to prop like we would use in <router-link to="/foo"> and the parent component for context. Without the context our RouterLink will unable to access this.$router , which takes away its functionality.
The Component’s corresponding DOM Element does not exist yet so we $mount() the Component to the old anchor, which replaces it.
Now the Component has an $el property to which we can copy attributes (eg., class) and inner content (its title).
Done! Click on the link and it should open the new page without reloading your single page application. Use to basics learned here and modify the functionality to your will.
Modifications
Render function allows us to select a different tag for our container through props (eg., section instead of div). Otherwise we could replace render() function with the more readable template:
Vue.js: replace <a> with <router-link> in dynamic HTML was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Marius D

Marius D | Sciencx (2022-01-07T03:12:53+00:00) Vue.js: replace <a> with <router-link> in dynamic HTML. Retrieved from https://www.scien.cx/2022/01/07/vue-js-replace-a-with-router-link-in-dynamic-html/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.