【问题标题】:Why isn't Vue reading my entire JSON object that I'm passing down through PHP as a prop?为什么 Vue 不读取我通过 PHP 作为道具传递的整个 JSON 对象?
【发布时间】:2016-06-15 11:40:26
【问题描述】:

我正在尝试使用道具将 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>

【问题讨论】:

  • 是的,我试过不转义引号,但 Vue 道具只会吐出{

标签: php json wordpress vue.js


【解决方案1】:

对于遇到此问题的任何人,接受答案的另一种方法是使用以下内容生成用于道具的字符串:

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会假设内容应该被解析为字符串而不是数据对象。

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    我不确定这是否是官方 vue.js 的“方式”,但这是我处理预加载数据的方式。

    首先获取你的结果集,不要担心任何编码/转义:

    $newsPostQuery = new WP_Query($args); 
    $posts = $newsPostQuery->posts[0];
    

    现在在 javascript 中,为这个预加载的数据创建一个全局变量。有时我会使用一个对象,以便以后可以在需要时轻松添加更多变量:

    <script>
    var preloaded = {
        'posts' : <?php echo json_encode($posts) ?>;
    }
    

    这样您就不必担心转义,引号没有问题。 json_encode 方法就够了。

    现在在您的 vue.js 代码中,当您想要访问这些数据时,可以参考 preloaded.posts,而不是尝试通过 prop 访问。

    道具非常适合简单的标量值。但是像这样的对象/json会很快变得混乱。

    【讨论】:

    • 马曼恩。这很好用,从来没有想过这个,非常感谢。
    • 是的,我之前试过了,但是时间限制让我无法标记它。
    猜你喜欢
    • 1970-01-01
    • 2018-02-12
    • 2016-12-09
    • 1970-01-01
    • 2022-01-26
    • 2022-01-26
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    相关资源
    最近更新 更多