3

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?

1
  • the span tag is used to group inline-elements in a document, I would suggest changing the type of tags Commented Mar 17, 2020 at 11:15

2 Answers 2

5

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)
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this! If I use the computed property would it be possible to create the filter within that or do I still need the separate filter?
If you need the filter in multiple places in your app, I would add it as a global filter. If not, you can just write the filter as a function outside your component or in a separate file and invoke it in your computed property like you would any function.
0

The values inside the html tags will treat as strings in Vue.js. This need to bind to the tag as 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.