[Vuejs]-Binding Vue.js to all instances of an element, without(?) using Components

2👍

Sounds like a great use case for a Custom Directive.

Vue allows you to register your own custom directives. Note that in Vue 2.0, the primary form of code reuse and abstraction is components – however there may be cases where you just need some low-level DOM access on plain elements, and this is where custom directives would still be useful.

<div id="app">
    <input type="text" name="myforminput" v-my-directive>
</div>

<script>
    Vue.directive('my-directive', {
        bind: function (el) {
            el.onblur = function () {
                el.classList.add('form__blurred');
            }
        }
    });

    var app = new Vue({
        el: '#app'
    });
</script>

You can also add the directive locally to a parent component, if it makes sense for your application.

Leave a comment