[Vuejs]-When should we use Vue.js's component

2đź‘Ť

âś…

For example, you use “alerts” a lot in your app. If you have experienced bootstrap, the alert would be like:

<div class="alert alert-danger">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    <strong>Title!</strong> Alert body ...
</div>

Instead of writing it over and over again, you can actually make it into a component in Vue:

Vue.component('alert', {
    props: ['type','bold','msg'],
    data : function() { return { isShown: true }; },
    methods : {
        closeAlert : function() {
            this.isShown = false;
        }
    }
});

And the HTML template (just to make it clear, I separate this from the Vue Comp above):

<div class="alert alert-{{ type }}" v-show="isShown">
    <button type="button" class="close" v-on="click: closeAlert()">&times;</button>
    <strong>{{ bold }}</strong> {{ msg }}
</div>

Then you can just call it like this:

<alert type="success|danger|warning|success" bold="Oops!" msg="This is the message"></alert>

Note that this is just a 4-lines of template code, imagine when your app uses lot of “widgets” with 100++ lines of code

Hope this answers..

👤Jihad Waspada

Leave a comment