100*_*ols 2 php wordpress json vue.js
我正在尝试使用 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 道具时,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>
Run Code Online (Sandbox Code Playgroud)
对于任何在这个问题上磕磕绊绊的人,接受答案的另一种方法是使用以下内容生成一个用于道具的字符串:
htmlentities(json_encode($data, JSON_HEX_QUOT), ENT_QUOTES);
Run Code Online (Sandbox Code Playgroud)
如果你愿意,你可以把它包装成一个像这样的函数:
function jsonToProp($data)
{
return htmlentities(json_encode($data, JSON_HEX_QUOT), ENT_QUOTES);
}
Run Code Online (Sandbox Code Playgroud)
把它放在你的functions.php 文件中。该调用将它与您的 vue 组件一起使用:
$posts = ...generate an array of data you want to pass into your component
<testposts :testprop="<?= jsonToProp($posts);?>"></testposts>
Run Code Online (Sandbox Code Playgroud)
注意在 prop 前面的冒号:你需要这个,否则 vue 会假设内容应该被解析为字符串而不是数据对象。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
3599 次 |
| 最近记录: |