繁体   English   中英

如何在 vue 上使用 v-html?

[英]How can I use v-html on the vue?

我尝试这样:

<template>
    ...
    <div v-html="test"></div>
    ...
</template>

<script>
export default {
  data: () => ({
    test: null,
  }),
  mounted () {
    let a = {country: "England:↵ - Liverpool↵ - Chelsea↵ - Arsenal↵ - MU↵ - City"}
    this.test = a.country
  }
}
</script>

结果 :

England:↵ - Liverpool↵ - Chelsea↵ - Arsenal↵ - MU↵ - City

我已经使用了 v-html,但这不起作用。 每个单词应该有一个新行

我怎么解决这个问题?

您需要从字面上替换 ,您可以通过以下方式进行:

let a = {
  country: "England:↵ - Liverpool↵ - Chelsea↵ - Arsenal↵ - MU↵ - City"
};
this.test = a.country.replace(/↵/g, '<br/>');

沙盒

我们不能直接使用降价字符。 所以我们需要使用替换功能用标签替换字符。

this.test = a.country.replace(/\u21B5/g,'<br/>')

如果您使用 Markdown,请尝试以下操作

 <template> <div v-html="$options.filters.markhtml(test)"></div> </template> <script> import marked from 'marked' export default { data(){ return { test: null, } }, mounted () { let a = {country: "England: \\n- Liverpool \\n- Chelsea \\n- Arsenal \\n- MU \\n- City"} this.test = a.country }, filters: { markhtml: function (markdown) { if (typeof markdown !== 'undefined') { return marked(markdown) } return null } } } </script>

您必须像代码中显示的那样使用marked并导入它。

下面是一个工作小提琴 希望我的回答有帮助

暂无
暂无

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

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