【问题标题】:Pass json to Vue component and loop将 json 传递给 Vue 组件并循环
【发布时间】:2018-07-23 06:03:32
【问题描述】:

这是预期的输出:

<div class="container">
    <div class="wrapper">
        <div class="title">Title 1</div>
        <div class="text"><p>Text 1</p></div>
    </div>
    <div class="wrapper">
        <div class="title">Title 2</div>
        <div class="text"><p>Text 2</p></div>
    </div>
    ...
</div>

这是我的 PHP 文件:

// Contains HTML markup
$array = [
    ['title' => 'Title 1', 'text' => '<p>Text 1<\/p>'],
    ['title' => 'Title 2', 'text' => '<p>Text 2<\/p>'],
    ...
];

<div class="container" data-content="'.json_encode($array).'">
    <list-item v-for="item in list" v-bind:list-prop="item" v-bind:key ="item.title"></list-item>
</div>

这是我的 JavaScript 文件:

var containers = document.querySelectorAll('.container');
if(containers.length > 0) {
    for(var i=0; i<containers.length; i++)
        buildList(containers[i]);
}

function buildList(el) {

    Vue.component('list-item', {
        props: ['listProp'],
        template: '<div class="wrapper"><div class="title">{{ listProp.title }}</div><div class="text">{{ listProp.text }}</div></div>'
    });

    var container = new Vue({
        el: el,
        data: {
            list: JSON.parse(el.dataContent)
        }
    });
}

我收到一个错误Unexpected token u in JSON at position 0 at JSON.parse 我显然做错了,但我不确定在哪里。很想知道是否有更好的方法来实现这一目标。我使用:prop 阅读了答案,但我不知道如何在我的情况下实现它。

【问题讨论】:

  • 您会立即获得对 “这是预期的输出” 的支持。好清爽!
  • 您不能将 JSON 编码为 HTML 属性,至少在不对引号进行编码的情况下是这样。您生成的 HTML 将类似于 data-content="["title":"Title 1",..."。注意到引号的问题了吗?
  • 每次调用buildList时,您似乎也在定义您的组件
  • 我想通了,但是以某种方式从函数中删除它会导致错误。我应该如何解决这个问题?

标签: javascript php vue.js vue-component


【解决方案1】:

我真的很讨厌这个建议,但是您可以在不使用 PHP 创建简单的 REST API 的情况下做到这一点。然后,一旦你在 window 对象上有了这个对象,你就可以在你的 Vue.js 代码中引用它。

// Contains HTML markup
<?php
$array = [
    ['title' => 'Title 1', 'text' => '<p>Text 1<\/p>'],
    ['title' => 'Title 2', 'text' => '<p>Text 2<\/p>'],
    ...
];
?>
<script>
  const titles = <?php echo $array; ?>
</script>
<div class="container">
    <list-item v-for="item in list" v-bind:list-prop="item" v-bind:key ="item.title"></list-item>
</div>

【讨论】:

    猜你喜欢
    • 2017-10-12
    • 2017-12-08
    • 2017-12-02
    • 2017-12-25
    • 2021-07-24
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多