【问题标题】:How can I able to display following using vue js?如何使用 vue js 显示以下内容?
【发布时间】:2018-04-15 20:34:54
【问题描述】:

我的JSON 是:

[{
  "name": "Health care",
  "cat_id": 1
}, {
  "name": "Education",
  "cat_id": 2
}, {
  "name": "Bakery",
  "cat_id": 3
}, {
  "name": "Software company",
  "cat_id": 4
}]

我的 vue js 脚本是。

<script>
  new Vue({
  el: '#categories' ,
  data: {
    articles: [],
  },
  mounted() {
    this.$nextTick(function() {
      var self = this;
      $.ajax({
            url: "https://",
            method: "GET",
            dataType: "JSON",
            success: function (e) {

                    self.articles = e.articles;
                    console.log(e.articles)

            },
        });
    })
  },

})

</script>

使用的html代码是

<div v-for="post in articles" id="categories">
                <div class="top">
                    <h4>Top Categories</h4>
                    <ul class="mov_list">
                        <li><i class="fa fa-star"></i></li>
                        <li>77</li>
                        <li><a href="">{{post.name}}</a></li>
                    </ul>   
                </div>
      </div>

这是我试图显示不同类别的地方。但是我遇到了一些错误。谁能帮我展示一下。我js很弱

【问题讨论】:

  • 你能把你得到的错误也粘贴一下吗?
  • 请提供更多相关信息,例如:输出是什么,遇到的错误类型等。
  • 我无法打印任何东西
  • 你知道如何在桌面浏览器上使用开发者工具吗?在大多数浏览器中,右键单击并检查,查找控制台选项卡。
  • 没有错误

标签: javascript html vue.js vue-component


【解决方案1】:

看起来像是范围问题。 self 必须在函数之外声明。我仍然相信您不需要指定回调。这样的事情就足够了:

<script>
new Vue({
    el: '#app',
    data: {
        articles: [],
    },
    mounted() {
        var self = this;

        $.ajax({
            url: "https://n2s.herokuapp.com/api/post/get_all_category/",
            method: "GET",
            dataType: "JSON",
            success: function(e) {
                self.articles = e.articles;
                console.log(e.articles)
            },
        });
    },
})
</script>

html:

<div id="app">
    <div v-for="post in articles">
        <div class="top">
            <h4>Top Categories</h4>
            <ul class="mov_list">
                <li><i class="fa fa-star"></i></li>
                <li>77</li>
                <li><a href="">{{post.name}}</a></li>
            </ul>   
        </div>
    </div>
</div>

干杯!

【讨论】:

  • 收到的消息是Cannot use v-for on stateful component root element because it renders multiple elements.。所以你必须将你的html代码包装在&lt;div id="app"&gt;之类的东西中,并在vue root实例中将el键更改为#app
猜你喜欢
  • 2018-04-01
  • 2018-05-01
  • 2021-09-12
  • 2016-12-29
  • 2018-04-25
  • 1970-01-01
  • 2018-04-02
  • 2017-06-07
  • 2018-03-23
相关资源
最近更新 更多