Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use quotes, brackets or nothing when passing props in Vue?

Tags:

vue.js

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?

like image 997
Kokodoko Avatar asked Sep 29 '17 12:09

Kokodoko


1 Answers

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.


With quotes:

<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


Without quotes:

<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.


As an object:

<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.

like image 101
thanksd Avatar answered Nov 15 '22 11:11

thanksd