How to define a directive with Vue 2.0 that always does Binding as string

Asked

Viewed 232 times

4

I’m starting now with Vue 2.0 and I’m creating directives so that I can manipulate the style of an element based on the content of that directive, so:

Vue.directive('margin', function (el, binding) {
    $(el).css('margin', binding.value);
});

My problem is that in order for me to give a Binding no value, I am obliged to leave the field always formatted as string, and this I see as unnecessary... so:

<div class="foo" v-margin="'auto'"></div>

If by chance I take the simple quotes from inside the Binding, occurs the error message:

[Vue warn]: Property or method "auto" is not defined on the instance but 
            referenced during render. Make sure to declare reactive data properties 
            in the data option. 

Is there any way to "force" the directive to always interpret my Binding as plain text? so I wouldn’t need to pass simple quotes from the 'auto'.

NOTE I have tried to define within the directive a toString() in the Binding parameter but without success, thus:

Vue.directive('margin', function (el, binding) {
    $(el).css('margin', binding.value.toString()); // <- toString();
});
  • And if you try String(binding.value)?

  • String(Binding.value) attempts to convert a variable to the String type which in this case is the same as Binding.value.toString().

  • Because I saw this, http://stackoverflow.com/questions/3945202/whats-the-difference-between-stringvalue-vs-value-tostring I thought it might work

  • It is a good logic to use String, but Vue interprets a null.toString() as "";D

  • I even find that odd, http://stackoverflow.com/documentation/vue.js/2368/custom-directives#t=201701091450173776812 and here https://vuejs.org/v2/guide/custom-directive.html seems to work just fine

1 answer

1


I believe that is not possible, according to "Directives in Depth":

For security reasons, in inline Expressions you can only access properties and methods present on the Current context Viewmodel and its parents.

But if you want it to work and you don’t see any problem seeing Warning, you can use binding.expression in place of bindig.value, the value will always be string, but obviously not the best option (because exchanging a single quote for a Warning does not seem to be a good exchange).

Browser other questions tagged

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