简体   繁体   English

在vue中用换行符分割字符串的问题

[英]Issue with splitting string with line break in vue

So I'm trying to set a filter to replace a hyphen with a <br> to spit it onto a new line.所以我试图设置一个过滤器来用<br>替换一个连字符来将它吐到一个新的行上。 I've created a filter like this:我创建了一个这样的过滤器:

filters: {

  splitRows: function (value) {
    if (!value) return ''
    value = value.toString()
    return value.replace('-', '</br>')
  }
}

And then接着

  <span class="Name">
      {{ product.title | splitRows }}
  </span>

However, this just prints the </br> instead of breaking the line.但是,这只是打印</br>而不是换行。 I'm new to vue so not sure what I'm doing wrong?我是 vue 新手,所以不确定我做错了什么?

The problem is not with your filter.问题不在于您的过滤器。 It's how you implement it.这就是你实现它的方式。 You need to use the v-html directive as seen in the Vue Documentation because you want to write html instead of text:您需要使用Vue 文档中看到的v-html指令,因为您想编写 html 而不是文本:

<span class="Name" v-html="$options.filters.splitRows(product.title)"/>

Please note that this is potentially dangerous as it allows for XSS attacks.请注意,这是潜在的危险,因为它允许 XSS 攻击。 If you write data that is not from you (for example data from a 3rd party API or data from a text field), take safety measures to strip malicious code.如果您编写的数据并非来自您本人(例如来自第 3 方 API 的数据或来自文本字段的数据),请采取安全措施去除恶意代码。

As you can see, there is no more pipe.如您所见,没有更多的管道。 The problem is that filters using the pipe syntax are not supported on anything other than text rendering.问题是使用管道语法的过滤器不支持文本渲染以外的任何内容。 You can still use your filter by accessing it via the $options object.您仍然可以通过$options对象访问过滤器来使用它。

A more elegant way to solve it would be using a computed property:一种更优雅的解决方法是使用计算属性:

export default {
  computed: {
    productTitle() {
      return this.$options.filters.splitRows(this.product.title)
    }
  }
}

The values inside the html tags will treat as strings in Vue.js. html 标签内的值在 Vue.js 中将被视为字符串。 This need to bind to the tag as html.这需要将标签绑定为html。

<span class="Name" v-html="product.title"></span>

Since the filter won't work in the bind section as normal, it can be called as follows:由于过滤器在绑定部分无法正常工作,因此可以如下调用:

<span class="Name" v-html="$options.filters.splitRows(product.title)"></span>

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

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