Vue.js/JavaScript - 是否可以在文本中插入链接/锚点? [英] Vue.js/JavaScript - Is it possible to insert a link/anchor inside a text?
问题描述
假设我有一个段落,其中包含从某个数据库中获取的一些文本:
{{ 文本 }}</p>
但是,本文可能包含对我的应用程序中其他页面的一些引用:
示例文本【参考】示例文本
所以我希望将这些引用转换为指向所述页面的链接:
示例文本<a href="/path/to/reference">参考示例文本</p>
我尝试在脚本中使用替换函数,如下所示:
text.replace(/\[(.+)\]/,"<a href='/path/to/$1'>$1</a>");
但是所有字符都被转义,导致锚定 html 代码显示在页面上.
有没有办法阻止字符被转义,或者甚至是另一种方法将文本中间的 [references] 变成指向另一个页面的工作链接?
如果您不希望 HTML 被转义,请使用 v-html
指令.
来自文档:
<块引用>双胡子将数据解释为纯文本,而不是 HTML.在为了输出真正的 HTML,你需要使用 v-html
指令:
示例:
var app = new Vue({el: "#app",数据:函数(){返回 {文本:有关详细信息,请参阅缺陷#12345"};}});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.min.js"></script><div id="应用程序"><p>{{text}}</p><p v-html="text"></p>
Let's say I have a paragraph with some text that I get from some database:
<p>
{{ text }}
</p>
However, this text may contain some references to other pages in my aplication:
Sample text [reference] sample text
So I would like these references to get turned into links to said pages:
<p>
Sample text <a href="/path/to/reference"> reference </a> sample text
</p>
I tried using the replace function in the script like this:
text.replace(/\[(.+)\]/,"<a href='/path/to/$1'>$1</a>");
But the characters all get escaped resulting in the anchor html code getting shown on the page.
Is there a way to stop the characters from being escaped, or even another way to turn [references] in the middle of the text into working links to another page?
If you don't want your HTML to be escaped, use the v-html
directive.
From the docs:
The double mustaches interprets the data as plain text, not HTML. In order to output real HTML, you will need to use the
v-html
directive:
Example:
var app = new Vue({
el: "#app",
data: function() {
return {
text: "See defect <a href='#'>#12345</a> for details"
};
}
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.min.js"></script>
<div id="app">
<p>{{text}}</p>
<p v-html="text"></p>
</div>
这篇关于Vue.js/JavaScript - 是否可以在文本中插入链接/锚点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!