In Vue, what is the purpose of v-model.trim

Viewed 11041

I am new to Vue and have learned v-model directive. To test what v-model.trim does I wrote the following code.

<template>
<p>Hello {{ myName }}</p>
<form>Name: <input type="text" v-model.trim="myName"/></form>
</template>

<script>
export default {
  data(){
    return{
      myName: "",
    };
  },
};
</script>

When I typed in " B o b" the output was "B o b". However, I found out that even when I don't use v-model.trim and just use v-model as follows

<template>
<p>Hello {{ myName }}</p>
<form>Name: <input type="text" v-model="myName"/></form>
</template>

<script>
export default {
  data(){
    return{
      myName: "",
    };
  },
};
</script>

it gives the exact same output. What is the purpose of .trim?

4 Answers

Per the docs

If you want whitespace from user input to be trimmed automatically, you can add the trim modifier to your v-model-managed inputs

v-model.trim="msg" is equal to doing msg = msg.trim() which removes white spaces before/after input.

Check this demo if you still have any doubts.

If you're looking for spaces in view(html), browser ignores the white spaces, try to check in the console.

In Javascript, .trim() is a String method to remove the spaces at the beginning and at the end of a string, so the same behavior is applied to v-model

It trims spacing from the beginning and end of strings.

So if you imagine you have an email input using model binding, and the user types their email with the a space after, that’s not going to be a valid email address. So the trim modifier truncates the spacing at the end.

trim() is a String method to remove the spaces at the beginning and at the end of a string, so the same behavior is applied to v-model

Related