DEV Community

MemphisNguyen
MemphisNguyen

Posted on

Passing object as props in VueJS

Hello everyone.
I'm currently working on a project require render JSX buts now I'm stucking with a problem that passing JSON object as props.

Even though VueJS supports passing a JSON object variable for the prop but not able to pass JSON object directly like below:

<Comp :property="{\"key": \"value\"}" />

Have you ever met this problem and having any suggestions for this?

I'm using encodeURIComponent and treat it as a string for now but it's not a pretty solution.

Top comments (4)

Collapse
 
thatbudakguy profile image
Nick Budak

This may not necessarily be what you want, but Vue supports a special syntax for passing an object and having each of its properties available separately to the child. You just need to:

<Comp v-bind=myJsonObj />

And the child will receive key.

Collapse
 
memphisnguyen profile image
MemphisNguyen

Actually the problem I got here is that I cannot use direct JSON object as a property without using a variable. v-bind is just a shorthand for defining property individually.

Collapse
 
oliver_ profile image
Oliver

Have you tried :property="JSON.parse(...)"?

Collapse
 
memphisnguyen profile image
MemphisNguyen

Hi Oliver, actually I've already use JSON.parse on it. But when looked in you answer, finally I understand where the problem come from.
JSON.parse map properties in to quotes and JSX doesn't except them even when they were escaped by backslash. Now I just need to convert " to &quot; then it works like charm even without JSON.parse . Even though it's still not really beautiful but a lot better than encodeURIComponent.
Thank you for the idea.