例如,我希望像Vue.http.apiCall
在内置插件中定义自己的函数的正确方法是什么?我应该为它创建自己的插件吗?
答案 0 :(得分:1)
不要使用vue-resource(Evan你已经宣布去年退休:link)。相反,您可以使用Fetch API,并且创建插件并不是必需的,只需将API调用包装在方法中:
const app = new Vue({
el: '#app',
data: {
getResult: undefined,
postResult: undefined,
samplePostData: {
title: 'foo',
body: 'bar',
userId: 1
}
},
methods: {
getSampleData() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then((result) => {
// sample callback
this.getResult = result;
})
},
postSampleData() {
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'post',
body: JSON.stringify(this.samplePostData)
}).then((response) => response.json())
.then((result) => {
/* will return
{
id: 101
}
*/
this.postResult = result
})
}
}
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.js"></script>
<div id="app">
<h2>Sample Get:</h2>
<button v-on:click="getSampleData()">Click to Get Sample data</button>
<div>{{getResult}}</div>
<h2>Sample Post:</h2>
<button v-on:click="postSampleData()">Click to Post Sample data</button>
<div>{{postResult}}</div>
</div>
&#13;
答案 1 :(得分:0)
对于Vue.js,您可以使用vue-resource
https://github.com/pagekit/vue-resource
使用此插件,您可以像这样进行外部API调用
// GET /someUrl
this.$http.get('/someUrl').then(response => {
// get body data
this.someData = response.body;
}, response => {
// error callback
});