为什么不是';t Vue读取我的整个JSON对象,我';我作为道具通过PHP传递信息?
我试图使用一个道具将JSON对象向下传递到Vue组件中。JSON对象是在收集页面所有帖子的WordPress查询中使用为什么不是';t Vue读取我的整个JSON对象,我';我作为道具通过PHP传递信息?,php,json,wordpress,vue.js,Php,Json,Wordpress,Vue.js,我试图使用一个道具将JSON对象向下传递到Vue组件中。JSON对象是在收集页面所有帖子的WordPress查询中使用JSON\u encode()计算的。然后,我使用PHP函数addcslashes()来转义所有双引号 当我在此变量上使用echo时,这是输出: {“ID\”:185,“post\u author\”:“1\”,“post\u date\:“2016-02-23 14:32:45\”,“post\u date\u gmt\”:“2016-02-23 14:32:45\” 但是,当
JSON\u encode()
计算的。然后,我使用PHP函数addcslashes()
来转义所有双引号
当我在此变量上使用echo
时,这是输出:
{“ID\”:185,“post\u author\”:“1\”,“post\u date\:“2016-02-23 14:32:45\”,“post\u date\u gmt\”:“2016-02-23 14:32:45\”
但是,当我将JSON字符串传递给我的Vue道具时,Vue调试器吐出的所有内容都是testprop:“{\\”
你知道为什么我不能在Vue属性中获得完整的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>
$newsPostQuery=newwp\u查询($args);
$posts=$newsPostQuery->posts[0];
$posts=json_encode($posts);
$posts=addcslashes($posts,“”);
回声“;
var_dump(员额);
回声“;
echo$员额;
?>
我不确定这是否是vue.js的官方“方式”,但以下是我处理预加载数据的方式
首先,只需获取结果集,不必担心任何编码/转义:
<script>
var preloaded = {
'posts' : <?php echo json_encode($posts) ?>;
}
现在在javascript中,为这个预加载的数据创建一个全局变量。有时我会使用一个对象,以便在以后需要时可以轻松添加更多变量:
htmlentities(json_encode($data, JSON_HEX_QUOT), ENT_QUOTES);
预加载变量={
“职位”:;
}
这样您就不必担心转义,引号也没有问题。json\u encode
方法就足够了
现在,在vue.js代码中,您可以在希望访问此数据时参考预加载.posts
,而不是尝试通过道具访问
对于简单的标量值来说,道具非常有用。但是像这样的对象/json会很快变得混乱。对于任何在这个问题上遇到障碍的人来说,另一种被接受的答案是使用以下方法生成一个字符串以在道具中使用:
function jsonToProp($data)
{
return htmlentities(json_encode($data, JSON_HEX_QUOT), ENT_QUOTES);
}
如果需要,可以将此un包装为如下函数:
$posts = ...generate an array of data you want to pass into your component
<testposts :testprop="<?= jsonToProp($posts);?>"></testposts>
将其保存在functions.php文件中。调用会将其与vue组件一起使用:
$posts=…生成要传递到组件中的数据数组
是的,我没有转义引号就试过了,但是Vue道具只会吐出{
Ma mannn。这很好,从来没有想到过,非常感谢。是的,当然,我之前试过,但时间限制阻止了我标记它。
$posts = ...generate an array of data you want to pass into your component
<testposts :testprop="<?= jsonToProp($posts);?>"></testposts>