9

I had the following code using v-text:

<h1 v-text="content.title"></h1>

Output:

Brand Name is B&amp;C

So I fixed it using v-html in the previous line:

<h1 v-html="content.title"></h1>

Output:

Brand Name is B&C

My question is the following:

Why does it works using v-html and not v-text? I already read the Vue documentation but I don't clearly understand the difference.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Ced
  • 1,293
  • 5
  • 23
  • 34
  • 1
    What is the point of downgrading my question without any reasons ? – Ced Nov 15 '18 at 14:00
  • 5
    People are mean I guess... welcome to stack overflow, we got cookies and a boat load of bitterness. Here's an upvote do you dont lose faith in stack overflow :) – Constantin Chirila Nov 15 '18 at 14:47

3 Answers3

7

v-text sets the textContent of the node. v-html sets the innerHTML of the element. &amp; is an HTML entity. If you want HTML entities interpreted and replaced, you need to have them interpreted as HTML and not text.

Roy J
  • 42,522
  • 10
  • 78
  • 102
  • 1
    I want to add that interpreting user's input as HTML poses a security risk – Gherman Nov 15 '18 at 13:31
  • 1
    Thank you ! Interesting @German why does it poses a security risk ? – Ced Nov 15 '18 at 14:04
  • 3
    I think he referrers to XSS (Cross site scripting) (here's a read: https://www.computerweekly.com/tip/Cross-site-scripting-explained-How-to-prevent-XSS-attacks). You just need to be carefull that the data you put inside the v-html it comes from a safe place and/or is sanitised properly, so you don't open your website to execute malicious scripts :) – Constantin Chirila Nov 15 '18 at 14:49
0

The v-html directive is used to update a element’s innerHTML with our data. This is what separates it from v-text which means while v-text accepts string and treats it as a string it will accept string and render it into HTML.

0

Simply stated, if you know js:

  • v-html == innerHTML
  • v-text == innerText