I’m attempting to pass a JSON object down into a Vue component using a prop. The JSON object is computed using json_encode()
on a WordPress query that gathers all posts for the page. I’m then using the PHP function addcslashes()
to escape all of my double quotes.
When I use echo
on this variable, this is the output:
{"ID":185,"post_author":"1","post_date":"2016-02-23 14:32:45","post_date_gmt":"2016-02-23 14:32:45"}
However, when I pass the JSON string down to my Vue prop, all the Vue debugger spits out is testprop: "{"
.
Any idea as to why I can’t get the full JSON object string within the Vue prop?
$newsPostQuery = new WP_Query($args);
$posts = $newsPostQuery->posts[0];
$posts = json_encode($posts);
$posts = addcslashes($posts, '"');
echo "<pre>";
var_dump($posts);
echo "</pre>";
echo $posts;
?>
<testposts testprop="<?php echo $posts; ?>"
></testposts>
<script type="text/javascript">
new Vue({
el: '.News-Feed',
components: {
testposts: {
template: '#test-posts',
props: ['testprop'],
ready() {
console.log(this.testprop);
this.testprop = JSON.parse(this.testprop);
},
}
}
});
</script>
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:
if you wanted you could wrap this un a function like so:
stick that in you functions.php file. the call use it with your vue component:
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:
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:
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.