简体   繁体   English

为什么 vhtml 不能正确渲染嵌套 <<?

[英]Why vhtml not rendering nested << properly?

I have an app that uses dynamic binding where <> is a dynamic way of getting value from API.我有一个使用动态绑定的应用程序,其中 <> 是从 API 获取价值的动态方式。 But when I am trying to render it in vhtml, its not even showing the parent element.但是当我试图在 vhtml 中呈现它时,它甚至没有显示父元素。 I want it like Name: <<Name>> .我希望它像 Name: <<Name>> How this can be achieved?如何做到这一点? . . I have attached the example code.我附上了示例代码。

 const app = new Vue({ el: '#app', data () { return { htmlText: '<p> Name: <<Name>> </p>' } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <span v-html="htmlText"></span> </div>

The error of yours was the << >> characters inside your string.您的错误是字符串中的<< >>字符。

 const app = new Vue({ el: '#app', data () { return { name: 'Max' } }, computed: { templateName() { // use a computed property or a method with template strings return `<p>Name: ${this.name} </p>` } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <p v-html="templateName" /> </div>

On top of Link's and Xlm's answers on vue: escape and render HTML string?除了LinkXlmvue 上的回答:escape and render HTML string?

Parse the incoming string with a regex that replaces < with &lt;使用将 < 替换为&lt;的正则表达式解析传入的字符串。 and > with &gt;和 > 与&gt;

Please note that this could be just a workaround .请注意,这可能只是一种解决方法 If you want a cleaner solution , you should do this in the API .如果您想要一个更清洁的解决方案,您应该在API中执行此操作。

In your case,在你的情况下,

 const app = new Vue({ el: "#app", data() { return { htmlText: "<p> Name: <<Name>> </p>", }; }, methods: { htmlToText(html) { return html.replace(/<</g, "&lt;&lt;").replace(/>>/g, "&gt;&gt;"); }, }, });
 <div id="app"> <span v-html="htmlToText(htmlText)"></span> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM