[Vuejs]-Vue.js and input's value that is never displayed

1πŸ‘

βœ…

I just wanted to share my views here. Personally I like to use v-model as it provides few added benefits like:

  • We can use .trim modifier with v-model which automatically trims whitespace from user input like:

      <input v-model.trim="msg">
    

This way you don’t need to write additional code to trim text like item = item.trim();. Few lines of code saved here.

  • Using this.newItem = '' we can easily clear out the previously entered text after button click using v-model reactivity feature. So, again less line of code instead of doing this.$refs.newItem.value = '';

  • Another advantage of using v-model is that, instead of doing

      <button @click="addItem($refs.newItem.value)">
    

You can simply call the function like:

    <button @click="addItem">

So, you can see these are the few benefits of using a simple v-model, which is mostly related to the developer experience (DX) point of view.

Working Demo:

const app = new Vue({
    el: '#app',
    data: {
        items: [
            'Chocolate',
            'Pizza',
            'Coca-Cola',
        ],
        newItem: ''
    },
    template: `
        <div>
            <div>{{ items.length }} item{{ items.length !== 1 ? 's' : '' }}</div>
            <ul>
                <li v-for="(item, index) of items">
                    {{ item }}
                    <button @click="deleteItem(index)">X</button>
                </li>
                <li>
                    <input type="text" placeholder="Item name" v-model.trim="newItem">
                    <button @click="addItem">+</button>
                </li>
            </ul>
        </div>
    `,
    methods: {
        addItem() {
            if (this.newItem === '') return;
            this.items.push(this.newItem);
            this.newItem = '';
        },
        deleteItem(index) {
            this.items.splice(index, 1);
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="app">
</div>

Leave a comment