【问题标题】:How can I use v-html on the vue?如何在 vue 上使用 v-html?
【发布时间】:2020-04-05 20:54:06
【问题描述】:

我尝试这样:

<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,但是不行。每个单词应该有一个新行

我该如何解决这个问题?

【问题讨论】:

  • 你应该用&lt;br&gt;换行而不是
  • 使用&lt;pre&gt; 标签或将style="white-space:pre-line" 添加到您的&lt;div&gt;。仅供参考, 不是换行符。它实际上是一个小的直角箭头字形
  • @Ahmad Mobaraki json 是 API 的响应
  • @Phil 是的。但是来自API的数据json。我只是为了获取数据
  • 不是 HTML

标签: html vue.js vuejs2 vue-component vuetify.js


【解决方案1】:

你需要从字面上替换,你可以这样做:

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

SANDBOX

【讨论】:

    【解决方案2】:

    如果您使用的是降价,请尝试以下操作

    <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 并像在代码中显示的那样导入它。

    下面是Working fiddle。希望我的回答对你有帮助

    【讨论】:

    • 你的代码 sn-p 说"Uncaught SyntaxError: Cannot use import statement outside a module"
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-08-19
      • 2017-11-12
      • 2020-12-12
      • 1970-01-01
      • 2021-10-03
      • 2020-07-01
      • 2021-04-18
      • 1970-01-01
      • 2020-10-03
      相关资源
      最近更新 更多