3

I have a text which has links inside in it. But I add these links(anchor elements) after the view is rendered(I fetch link information from server and insert anchor element for each word). Each link has call to a function inside my container, but I guess because the links are inserted to the page after render, they don't get bound to the model methods. How can I get these links click events bound to the method after render?

Here is my component :

<div class="info-text" v-html="descriptionShown"></div>

enter image description here

2
  • check this Commented Sep 18, 2021 at 8:36
  • Yeah, it's the same link Igor provided, it worked quite well. Commented Sep 18, 2021 at 17:34

1 Answer 1

2

Unfortunately you can't do this. Vue's v-html directive binds the content as raw HTML, rather than vue template syntax like you would normally use, which means vue does not interpret any data bindings, such as events. From the vue guide:

The contents of the span will be replaced with the value of the rawHtml property, interpreted as plain HTML - data bindings are ignored. Note that you cannot use v-html to compose template partials, because Vue is not a string-based templating engine.

Also, it's generally considered something to avoid as this would leave your website open to XSS injection unless you're very careful about how you use the v-html property and make sure it never touches user inputted content.

Your best bet would be to parse the data into an object or array as needed and have that be handled by a component with a v-for loop or similar, the data being passed as a prop. E.g. you might have something like this:

[{text: "Some text content", link: ''},{text: "Followed by a link.", link: "example.com"}]

And have the component operate over that with a v-for and then generate either plain text or an anchor tag depending on the link contents, or whatever other properties you would want to define, such as emitting a specific event with $emit('eventName') which you can capture where the component is called.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer, but I'll go with Igor's answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.