2👍
The use case for both are the same. But the first one is just a short-hand code:
<div v-myDirective:foo.a.b="some value">
But remember foo.a.b
has a
and b
modifier and the directives returns true for them when it presents inside the directive.
When you just use foo.a
, then the b
modifier is not present and it returns false.
if (binding.modifiers.a) {
// do something a
}
if (binding.modifiers.b) {
// do something b
}
But in an object syntax, you can do more thing rather than just a true value check.
<div v-myDirective="{arg: 'foo', a:'some string', b:100, value: 'some value'}">
This way, you can check if a
has ‘some string’ and b
has 100 in your directive function.
if (binding.value.a == 'some string') {
// do something a
}
if (binding.value.b == 100) {
// do something b
}
Most of us prefer short-hand syntax and I do as well. So, whenever you need to check if modifier is present or not, use short-hand syntax. And use object syntax when you need more complex check than just true value check.
0👍
Programming usability/convenience, that’s all.
The reason one would prefer v-directive:foo="bar"
instead of v-directive="{foo: bar}"
is the same people prefer :prop="val"
instead of v-bind:prop="val"
. Convenience.
Same with v-on:click
and @click
.
Using the declarative way (instead of the “value” way) can be much more readable and make much more sense for the end user (the programmer). The declarative way separates much better what is “metadata” and what is “payload” for the directive.
If the end user is a designer (not used to JavaScript’s object notation), I’d argue this makes an even greater difference.
The “value” notation becomes much more error prone the more you have options:
v-directive="{a: 1, b: '123', c: message, d: 'false'}"
Will people really remember to quote '123'
correctly so it means a string? Will they do it while not quoting a
‘s value? Will they always remember they should quote one but not the other? Is it clear to the user that message
there will be the value of this.message
and not the string "message"
? If d
is a boolean property, how bad is it to quote it (by accident)?
Lastly, another important point that may have directed Vue’s designers is that they try to make available to custom directives the very behaviors available on native directives. And all those modifiers/args exist in native directives (e.g. v-bind:address.sync="myAddressProp"
).