我正在尝试使用 prop 将 JSON 对象向下传递到 Vue 组件中。 JSON 对象是使用 json_encode()
在 WordPress 查询上计算的,该查询收集页面的所有帖子。然后我使用 PHP 函数 addcslashes()
来转义我所有的双引号。
当我在这个变量上使用 echo
时,这是输出:
{\"ID\":185,\"post_author\":\"1\",\"post_date\":\"2016-02-23 14:32:45\",\"post_date_gmt\":\"2016-02-23 14:32:45\"}
但是,当我将 JSON 字符串向下传递到我的 Vue prop 时,Vue 调试器吐出的所有内容都是 testprop: "{\\"
。
知道为什么我无法在 Vue prop 中获取完整的 JSON 对象字符串吗?
$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>
最佳答案
对于遇到这个问题的任何人,接受答案的另一种方法是使用以下内容生成一个字符串以用于 prop:
htmlentities(json_encode($data, JSON_HEX_QUOT), ENT_QUOTES);
如果你愿意,你可以像这样把它包装成一个函数:
function jsonToProp($data)
{
return htmlentities(json_encode($data, JSON_HEX_QUOT), ENT_QUOTES);
}
将其粘贴到您的 functions.php 文件中。该调用将它与您的 vue 组件一起使用:
$posts = ...generate an array of data you want to pass into your component
<testposts :testprop="<?= jsonToProp($posts);?>"></testposts>
注意 prop 前面的冒号 : 你需要这个,否则 vue 会假定内容应该被解析为字符串而不是数据对象。
希望这对您有所帮助!
关于php - 为什么 Vue 不读取我通过 PHP 作为 Prop 传递的整个 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35750278/