0

I have a Vue Filter to truncate my text when it becomes too long. However, I can not get it to work and have no idea why. Any help welcome.

var app = new Vue({
  el: '#app',
  data: {
    text: 'Bark bark and a woof woof'
  }
})

Vue.filter('truncate', function (value, size) {
  if (!value) return '';
  value = value.toString();

  if (value.length <= size) {
    return value;
  }
  return value.substr(0, size) + '...';
});

My HTML is as follows;

<div id="app">
 <p>{{text | truncate(8) }}</p>
</div>
2
  • so what is the current result you get ? It still return the full text ? Commented May 21, 2020 at 14:14
  • Yes, It still returns the full text. jsfiddle.net/68jyhk0t Commented May 21, 2020 at 14:17

1 Answer 1

2

I just check your fiddle, the reason is you need to declare the Filter before creating the Vue object

Vue.filter('truncate', function (value, size) {
  if (!value) return '';
  value = value.toString();

  if (value.length <= size) {
    return value;
  }
  return value.substr(0, size) + '...';
});

var app = new Vue({
  el: '#app',
  data: {
    text: 'Bark bark and a woof woof'
  }
})

changing the order should works now

Sign up to request clarification or add additional context in comments.

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.