php - 为什么 Vue 不读取我通过 PHP 作为 Prop 传递的整个 JSON 对象?

标签 php json wordpress 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 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/

相关文章:

php - 将多个匹配的正则表达式合并为一个并得到匹配的

php - 当所选选项更改时,我是否应该动态生成数据库查询?

php - 生成唯一的数组值

json - 无法修复 wordpress 中格式错误的 JSON

wordpress - 如何让Wordpress支持.jfif图片上传?

php - 使用 MySQL LIKE 语句查找相关文章

php - 在 php 函数中使用循环并使用 JSON 返回结果

javascript - 更改 amCharts 数据的粒度

php - 当特定产品类别位于 Woocommerce 购物车中时有条件地应用 CSS 样式

php - WordPress 使用自定义表格数据的永久链接创建自定义页面