javascript - VueJS 连接外部数据

标签 javascript json rest vue.js

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

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: 并将其命名为 posts?

最佳答案

您可以创建一个方法,该方法将调用远程 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);
      });
    }
  }

并且您可以从已安装的 block 中调用此方法,这将在您的组件已安装时获取并分配帖子。

mounted () {
  this.getPosts()
}

你也可以看看我的answer关于如何使用axios这是一个用于调用 api 的 HTTP 客户端

参见工作笔here .

关于javascript - VueJS 连接外部数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41489314/

相关文章:

javascript - 如何在 AngularJS 中使用 ng Repeat 获取嵌套的 JSON 数据

ajax - 如何在 axios 中捕获状态 = 已取消?

javascript - 如何在 javascript 中访问父函数闭包?

javascript - 如何停止功能 doajax_red 和 doajax_blue ,当检查单选按钮?

javascript - 如何根据状态更改颜色字体?

javascript - 我如何使用 jquery 获取特定文本

ios - RestKit 响应未正确映射

jquery - 戈朗 : Extracting XML Issue

mysql - 无法使用 Dreamfactory 连接到远程 SQL 数据库

c# - 如何格式化Json输出?