我正在学习 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/