Skip to content
Advertisement

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. 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. I’m new to vue so not sure what I’m doing wrong?

Advertisement

Answer

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:

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

Please note that this is potentially dangerous as it allows for XSS attacks. 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.

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.

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)
    }
  }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement