Trim whitespace in NuxtJS/VueJS

In VueJS/NuxtJS, when you add a line break into your syntax for readability like so:

<!-- NuxtJS example -->
<nuxt-link :to="{ name: 'profile', params: { pseudo }">
   {{ pseudo }}
</nuxt-link>

<!-- VueJS example -->
<a :href="`/profile/${pseudo}`">
   {{ pseudo }}
</a>

The final link will contains leading and a trailing white space around the pseudo, which is ugly when the link is underlined:  Maz 
And further more if a list of pseudo is displayed separated by commas:  Maz ,  Vince ,  Thomas ,  Gladiator 

If you search over there, you will find some tiny accurate resources but none worked for me: The Vue template compiler does include a whitespace option which could be set to condense but if you read its definition, it only does what we want to fix:

If set to 'condense':

  • A whitespace-only text node between element tags is removed if it contains new lines. Otherwise, it is condensed into a single space.
  • Consecutive whitespaces inside a non-whitespace-only text node are condensed into a single space.

meaning:

<!-- This: -->
<span>    </span>
<!-- Becomes: -->
<span></span>

<!-- But this: -->
<span>
   Pseudo
</span>
<!-- Becomes: -->
<span> Pseudo </span> <!-- Note the extra space before and after `Pseudo`

The only way I found to solve this problem was to use v-text directive:

<!-- NuxtJS example -->
<nuxt-link :to="{ name: 'profile', params: { pseudo }" v-text="pseudo" />

<!-- VueJS example -->
<a :href="`/profile/${pseudo}`" v-text="pseudo" />

Note that we used v-text and not v-html to not open a door to XSS attacks!

Comments

Be the first to post a comment!

Add a comment

Preview