Home > Back-end >  Truncate words (chars) in vuejs 3
Truncate words (chars) in vuejs 3

Time:01-01

How to truncate words or chars in VueJs 3 ? I searched some answers but didn't work for me. For example if description words length more than 200 , it should display 200 words and ... at the end

What I tried so far..

<p>{{ announcement.description | truncate(200) }}</p>

<script>
export default {
data() {
    return {
      announcement: {},
    }
  },
computed:{
    truncate(value, length) {
        if (value.length > length) {
            return value.substring(0, length)   "...";
        } else {
            return value;
          }
    }
  }
}
</script>

CodePudding user response:

What you are looking for is a method, not a computed property. A computed property is used to declaratively describe a value that depends on other values. Move your code to methods and pass the argument with the length it should work.

    methods: {
       truncate(value, length) {
        if (value.length > length) {
            return value.substring(0, length)   "...";
        } else {
            return value;
          }
      }
   }

And just call this method from the template:

truncate(announcement.description,200)

You can read about correct usage of computed from here: https://vuejs.org/v2/guide/computed.html

  • Related