首页 > 解决方案 > 如何在 html 中使用 Vue.js 从 Web 服务中获取数据?

问题描述

我想用 vue.js 从 web 服务中获取数据。但是不能取数据。不安装node.js可以用vue.js吗?你能帮我吗?先感谢您..

<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/vue@2.0.3/dist/vue.js"></script>   <script src="https://unpkg.com/vue-resource@1.0.3/dist/vue-resource.min.js"></script>        
</head>
<body>
     <div id="app">             
        <table border=1>
           <thead>
             <tr>
             <th>title</th>
             </tr>
            </thead>
             <tr id="app">
             <td>{{data.title}}</td>
             </tr>
         </table>           
     </div>
<script type="text/javascript">
var dataURL = 'https://swapi.co/api/films/?format=json';

var App = new Vue({
  el: '#app',
  data: {
    posts: [] // initialize empty array
  },
  mounted() { 
    var self = this 
    $.getJSON(dataURL, function(data) {
      self.posts = data.results;
    });
  }
})
</script>
</body>
</html>

标签: javascriptvue.js

解决方案


您正在添加 Vue 资源,但使用的是 Jquery。查看:https ://github.com/pagekit/vue-resource

我还制作了一个 v-for 循环来遍历表中的帖子数组。

注意:在使用 VueJS 时,确实没有需要 JQuery 的情况。

<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/vue@2.0.3/dist/vue.js"></script>   <script src="https://unpkg.com/vue-resource@1.0.3/dist/vue-resource.min.js"></script>        
</head>
<body>
     <div id="app">             
        <table border=1>
           <thead>
             <tr>
             <th>title</th>
             </tr>
            </thead>
             <tr v-for="item in posts">
             <td>{{item.title}}</td>
             </tr>
         </table>           
     </div>
<script type="text/javascript">
var dataURL = 'https://swapi.co/api/films/?format=json';

var App = new Vue({
  el: '#app',
  data() {
    return {
      posts: [] // initialize empty array
    }
  },
  mounted() { 
    this.$http.get(dataURL).then(res => {
     this.posts = res.body.results
    });
  }
})
</script>
</body>
</html>


推荐阅读