javascript - 如何在 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>
解决方案
您正在添加 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>
推荐阅读
- c# - ASP.NET Core 2.1 Swagger(swashbuckle) Url 模板可选参数
- sql - SQL 查询在 WHERE CLAUSE 中执行更多记录
- azure-sql-managed-instance - SQL MI - 在启用加密的数据库上手动备份失败
- wpf - WPF 值在 ValueConverter 中为空
- common-lisp - 如何在定义条件对象中获取和传递哈希表?
- ionic-framework - 如何检查离子输入是否为空?
- git - 如何在另一个 git 分支上 grep 文件?
- javascript - 无法使用 fetch 和 reactjs 获取列表中的数据
- mysql - 名称 [jdbc/mydb] 未绑定在此上下文中。找不到 [jdbc]
- javafx - JavaFX外部拖放区分复制和移动