Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

javascript - Localizing html content in vue

So I have been using v-html tag to render the html in my vue pages. But I encountered a string which was a proper html file and it contained text kind of like this:

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
....
<style>
</style>
</head>

<body style="....">
</body>

</html>

The problem is, I have the v-html on a div, but this code starts affecting the whole page and adds its styling to the whole page and not only to that specific div.

I tried adding "scope" to the style tags but it did not work. Maybe because there's also a style inline tag on body?

I need to find a way to make the html affect only on the div it is on, and not the whole page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your best bet would probably be to have a better control over the HTML added using v-html. I would suggest to parse it before and keep only the <body> tag. You could do it using a regex, but it would be easier using a dom parser lib. Example with DomParser:

const DomParser = require("dom-parser");
const parser = new DomParser();

export default {
  // ...
  computed: {
    html() {
      const rawHtml = "<html><body><div>test</div></body></html>"; // This data should come from your server
      const dom = parser.parseFromString(rawHtml);
      return dom.getElementsByTagName("body")[0].innerHTML;
    }
  }
}

Please note that it is an oversimplified solution as it does not handle the case where there is no <body> tag.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...