Javascript 连接到外部数据的VueJS
我正在学习VueJs。我做了一个简单的项目,你可以在这里看到:Javascript 连接到外部数据的VueJS,javascript,json,rest,vue.js,Javascript,Json,Rest,Vue.js,我正在学习VueJs。我做了一个简单的项目,你可以在这里看到: var vuePosts=新的Vue({ el:“#vue posts”, 数据:{ 职位:[ {title:'title 1',body:'message 1'}, {title:'title 2',body:'message 2'} ] } }) Vue测试 {{post.title} {{post.body} 您可以创建一个方法,该方法将调用远程API,获取数据并将其分配给数据变量this.posts。源于问题的
var vuePosts=新的Vue({
el:“#vue posts”,
数据:{
职位:[
{title:'title 1',body:'message 1'},
{title:'title 2',body:'message 2'}
]
}
})
Vue测试
-
{{post.title}
{{post.body}
您可以创建一个方法,该方法将调用远程API,获取数据并将其分配给数据变量this.posts。源于问题的代码如下所示:
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块调用这个方法,当您的组件被挂载时,它将获取并分配POST
mounted () {
this.getPosts()
}
您还可以查看my on how to use,它是用于进行api调用的HTTP客户机
请先看工作笔。谢谢您的时间,saurabh。我曾尝试添加您给我的这段代码,但一直无法使其正常工作。请查看我的代码笔@noway我对你的笔做了一些小改动,请检查。非常感谢你的帮助,我正在保存你的代码并学习它。