javascripthtmlvue.jsvuejs2vue-filter

Render html using filter


I need to write a filter which renders html tags. This is my filter:

filters: {
  limitStrLength: function (value, maxLength) {
    if (value && value.length > maxLength) {
      let partialVal = value.substr(0, maxLength) + "...";
      return "<span title='" + value + "' >" + partialVal + "</span>";
    } else {
      return value;
    }
  }
}

My problem is that I do not manage to render the raw html.

If I simply do:

<div>{{ productName  | limitStrLength(6) }}</div>

The html tags are rendered as string (i.e., I see on screen something like <span title=...).

I also tried using v-html attribute:

<div v-html="productName | limitStrLength(6)"></div>

But I get an error:

Property or method "limitStrLength" is not defined on the instance but referenced during render.

Any idea?


Solution

  • Try this:

    <div v-html="$options.filters.limitStrLength(productName, 6)"></div>
    

    Source: Github issue