【问题标题】:VueJS connecting to external dataVueJS 连接外部数据
【发布时间】:2017-05-20 05:58:29
【问题描述】:

我正在学习 VueJ。我做了一个简单的项目,你可以在这里看到:

var vuePosts = new Vue({
  el: '#vue-posts',
  data: {
    posts: [
      {title: 'title 1', body: 'message 1'},
      {title: 'title 2', body: 'message 2'}
    ]
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div class="vue-test" id="vue-posts">
  <h1>Vue Test</h1>
  <ul v-for="post in posts">
    <li>
      <h1>{{post.title}}</h1>
      <p>{{post.body}}</p>
      <hr />
    </li>
  </ul>
</div>

如您所见,我只是在做一个 v-for 并为 js 文件发帖。

我的问题是我应该怎么做我想使用来自外部来源的数据,例如

https://jsonplaceholder.typicode.com/posts

如何将数据导入我的data: 并将其命名为帖子?

【问题讨论】:

    标签: javascript json rest vue.js


    【解决方案1】:

    您可以创建一个方法,该方法将调用远程 API,获取数据并将其分配给您的数据变量 this.posts。受here 问题启发的代码如下所示:

      methods: {
        getPosts: function() {
          var that = this
          $.ajax({
            url: 'https://jsonplaceholder.typicode.com/posts',
            method: 'GET'
          }).then(function (response) {
            if(response.error) {
              console.err("There was an error " + response.error);
            } else {
              console.log(response.posts);
              this.posts = response.posts
            }
          }).catch(function (err) {
            console.error(err);
          });
        }
      }
    

    您可以从挂载的块中调用此方法,这将在您的组件被挂载时获取并分配帖子。

    mounted () {
      this.getPosts()
    }
    

    您还可以查看我的answer,了解如何使用axios,这是一个用于进行api调用的HTTP客户端

    见工作笔here

    【讨论】:

    • 首先感谢您的时间 saurabh。我试图添加你给我的这段代码,但我无法让它工作。请看我的代码笔codepen.io/fparedlo/pen/LxEqGX
    • @noway 我对你的笔做了一些小改动,请查看this
    • 非常感谢您的帮助,我正在保留并研究您的代码。
    猜你喜欢
    • 2012-01-08
    • 2023-01-03
    • 2021-02-26
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 2021-01-25
    • 2013-05-21
    相关资源
    最近更新 更多