Why isn't Vue reading my entire JSON object that I'm passing down through PHP as a prop?
For anyone stumbling on this questions, an alternative approach to the accepted answer is to use the following to generate a string for use in a prop:
htmlentities(json_encode($data, JSON_HEX_QUOT), ENT_QUOTES);
if you wanted you could wrap this un a function like so:
function jsonToProp($data){ return htmlentities(json_encode($data, JSON_HEX_QUOT), ENT_QUOTES);}
stick that in you functions.php file. the call use it with your vue component:
$posts = ...generate an array of data you want to pass into your component<testposts :testprop="<?= jsonToProp($posts);?>"></testposts>
Note the colon : in front of the prop - you need this or vue will assume the content should be parsed as a string rather than as a data object.
Hope this helps!
I'm not sure if this is the official vue.js "way" but here's how I handle preloading data.
First just grab your result set, don't worry about any encoding/escaping yet:
$newsPostQuery = new WP_Query($args); $posts = $newsPostQuery->posts[0];
Now in javascript, create a global variable for this preloaded data. Sometimes I use an object so I can easily add more variables later if needed:
<script>var preloaded = { 'posts' : <?php echo json_encode($posts) ?>;}
This way you don't have to worry about escaping, there are no issues with quotes. The json_encode
method is enough.
Now in your vue.js code, you can refer to preloaded.posts
when you want to access this data, instead of trying to access via a prop.
Props are great for simple scalar values. But it gets messy fast with objects/json like this.