I'm building a Vue template, and passing props into components. I find it somewhat confusing to decide when I need brackets, quotes or none of those, to pass a variable down into a component. I have seen these three notations:
<status-view v-bind:total=total></status-view>
<status-view v-bind:total="total"></status-view>
<status-view v-bind:total="{total}"></status-view>
What exactly is the difference between these types of notations?
Your first two examples are binding the <status-view> component's total prop to the value of total in the context of the current template's scope.
Your last example is binding the <status-view> component's total prop to the value of {total} in the context of the current template's scope.
In this case, {total} is the ECMAScript2015 object initializer shorthand for { total: total } (an object that has a key total with a value equal to the value of the total property).
To make it easier to reason about, let call the component <child>, the component's prop foo and the property we are binding bar.
<child v-bind:foo="bar"></child>
binds the value of the bar property in the current scope to the child's foo prop
anything within the quotes will be evaluated as a javascript expression. So v-bind:foo="bar + 1" (given bar equals 1) would bind the value 2 to the child's foo prop.
I would recommend always binding a property value to a child component's prop this way
<child v-bind:foo=bar></child>
also binds the value of the bar property in the current scope to the child's foo prop
as Roy J pointed out, attribute quotes are optional in HTLM5. So this will be evaluated exactly the same as above. For consistency's sake, I would still use quotes.
<child v-bind:foo="{bar}"></child>
binds an object { bar: bar } to the child's foo prop
for instace, if bar equaled 'test', the child's foo prop would be { bar: 'test' }
Here's the documentation for v-bind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With