8

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?

1 Answer 1

7

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.

4
  • Ah, of course { bar } is just object shorthand :) So is there a reason to use quotes at all?
    – Kokodoko
    Commented Sep 29, 2017 at 13:26
  • 1
    As I said in my answer I would always use quotes (sorry, I switched your order maybe that was confusing)
    – thanksd
    Commented Sep 29, 2017 at 13:31
  • 3
    Attribute quotes are optional in HTML5
    – Roy J
    Commented Sep 29, 2017 at 14:15
  • When you bind, you should bind to a single variable, not a very complicated javascript expression. So I disagree with putting quotes there because it enforces that you have simple variables there.
    – Pui Ho Lam
    Commented Mar 22, 2023 at 18:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.