Display only a part of the name if characters exceed a limit in Vue.js

Here is my answer fiddle : ANSWER-DEMO

<div id="app">
  <div v-if="username.length<8">Welcome, {{ username }}</div>
  <div v-else>Welcome, {{ username.substring(0,8)+".." }}</div>
</div>

you want a computed property that check if the string is > 8 chars and make modifications and use that computed property in your template.

new Vue({
  el: '#app',
  data: {
    username: 'AVERYLONGGGNAMMEEE'
  },
  computed: {
    usernameLimited(){
      if ( this.username.length > 8 ) {
        return this.username.substring(0,8) + '...'
      } else {
        return this.username
      }
    }
  }
})

UPDATE VUE 3

Filters have been removed from Vue 3.

With Vue3, you must use globalProperties if you want to be able to use a function in several components.

app.config.globalProperties.$filters = {
  str_limit(value, size) {
    if (!value) return '';
    value = value.toString();

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

Use it like that:

{{ $filters.str_limit(8) }}

FOR VUE 2

You can also register a filter.

You can reuse the function simply in your project.

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

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

Use it like that :

<div id="app">
  <div>Welcome, {{ username | str_limit(8) }}</div>
</div>

You can do this by using computed properties.

new Vue({
 el: '#app',
 data: {
  username: 'AVERYLONGGGNAMMEEE'
 },

 computed: {
   strippedUsername: function(){
      if(this.username.length > 5) {
         return this.username.slice(0,4);
      }
      return this.username;
   }
}


});