首页 > 解决方案 > 文本仅显示在 td 元素中而不是 HTML

问题描述

我有一个 table td 元素,它只显示这个 ,我不需要它看起来像那样,而只是作为一个空格。

new Vue({
  el: '#app2',
  beforeCreate: function() {

  },
  created: function() {

  },
  mounted: function() {},
  data: {
    itemPriceList: [],
    orderItems: [{
        globalGroupName: "-- ABC"
      },
      {
        globalGroupName: "-- CDE"
      },
      {
        globalGroupName: "--- FGH"
      },
      {
        globalGroupName: "- IJK"
      },
      {
        globalGroupName: "-- LMN"
      }
    ],
    priceList: null
  },
  methods: {
    GetOrderItems: function() {

    },
    ReplaceDashesInGlobalGroups: function(globalGroupName) {
      if (globalGroupName[0] === "-") {
        // Remove leading dashes and replace with a blank space
        console.log("ReplaceDashesInGlobalGroups");
        return globalGroupName.replace(/-(?![a-zA-Z])|-(?=\s|-)/g, ' ');
      }
      return globalGroupName;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />

<div id="app2">
  <table class="table table-striped table-bordered table-hover" style="width:350px;">
    <thead class="thead-dark">
      <tr>
        <th width="235px"><label>Global Name</label></th>
      </tr>
    </thead>
    <tbody>
      <template v-for="global in orderItems">
                    <tr>
                        <td>{{ ReplaceDashesInGlobalGroups(global.globalGroupName) }}</td>
                    </tr>
                </template>
    </tbody>
  </table>
</div>

标签: vue.js

解决方案


试试这个:

<td v-html="ReplaceDashesInGlobalGroups(global.globalGroupName)"></td>

现在应该将其呈现为 HTML 而不仅仅是纯文本。请注意,这会使您面临 XSS 攻击。

资料来源:文档

更新元素的 innerHTML。请注意,内容是作为纯 HTML 插入的——它们不会被编译为 Vue 模板。如果您发现自己尝试使用 v-html 编写模板,请尝试使用组件来重新考虑解决方案。

在您的网站上动态呈现任意 HTML 可能非常危险,因为它很容易导致XSS 攻击。仅用于v-html 受信任的内容,切勿用于用户提供的内容。

单文件组件中,scoped样式不会应用于里面的内容v-html,因为 Vue 的模板编译器不会处理 HTML。如果您想v-html使用作用域 CSS 来定位内容,则可以改用 CSS 模块或具有<style>手动作用域策略(如 BEM)的附加全局元素。


推荐阅读