Set a default value in Binding.value Vue Directive

Asked

Viewed 29 times

1

People are creating a simple Directive and wanted to know how to put a value if the binding.value for undefined in a simpler way, much like the Vue Component in which you can set the defalut value?

Example:

Vue.directive('color', {
    bind: function (el, binding) {
        var prop = binding.value,
            color = prop.color

            if(color == undefined) color = '#FFFFFF'

        el.style.backgroundColor = color
    }
})

1 answer

1


More objectively and directly you can solve so:

Vue.directive('color', {
    bind: function (el, binding) {
        var prop = (binding.value || { color: '#FFFFFF' }),
            color = prop.color

        // Não vai mais precisa dessa checagem.
        //if(color == undefined) color = '#FFFFFF'

        el.style.backgroundColor = color
    }
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.