Fai*_*med 82 service vue.js vuejs2
我想将所有与服务器通信的函数放入VueJS中并将数据提取到一个可重用的文件中.
插件似乎不是最好的选择.模板较少的组件..?
Ota*_*kov 50
有4种方式:
Sau*_*abh 34
我使用axios作为HTTP客户端进行api调用,我gateways在我的src文件夹中创建了一个文件夹,我为每个后端放置了文件,创建了axios实例,如下所示
myApi.js
import axios from 'axios'
export default axios.create({
baseURL: 'http://localhost:3000/api/v1',
timeout: 5000,
headers: {
'X-Auth-Token': 'f2b6637ddf355a476918940289c0be016a4fe99e3b69c83d',
'Content-Type': 'application/json'
}
})
Run Code Online (Sandbox Code Playgroud)
现在在您的组件中,您可以拥有一个从api获取数据的函数,如下所示:
methods: {
getProducts () {
myApi.get('products?id=' + prodId).then(response => this.product = response.data)
}
}
Run Code Online (Sandbox Code Playgroud)
我假设你想在多个组件中重用这个方法,你可以使用vue.js的mixins:
Mixins是为Vue组件分发可重用功能的灵活方式.mixin对象可以包含任何组件选项.当组件使用mixin时,mixin中的所有选项将"混合"到组件自己的选项中.
因此,您可以在mixin中添加一个方法,它将在所有组件中可用,其中mixin将被混合.请参阅以下示例:
// define a mixin object
var myMixin = {
methods: {
getProducts () {
myApi.get('products?id=' + prodId).then(response => this.product = response.data)
}
}
}
// define a component that uses this mixin
var Component = Vue.extend({
mixins: [myMixin]
})
// alternate way to have a mixin while initialising
new Vue({
mixins: [myMixin],
created: function () {
console.log('other code')
}
})
Run Code Online (Sandbox Code Playgroud)
Bel*_*dak 29
我主要使用的是Vue资源.
1.我创建新文件,我使用Vue.http.xxx.So 连接到API端点.假设我们有端点输出posts.Create项目中的新目录,我调用它services,然后创建名为PostsService.js- content的文件如下所示:
import Vue from 'vue'
export default {
get() {
return Vue.http.get('/api/posts)
}
}
Run Code Online (Sandbox Code Playgroud)
然后我转到我想要使用此服务的组件,并导入它
import PostsService from '../services/PostsService'
export default {
data() {
return {
items: []
}
},
created() {
this.fetchPosts()
},
methods: {
fetchPosts() {
return PostsService.get()
.then(response => {
this.items = response.data
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
有关此方法的更多信息,请随时在GitHub上查看我的回购https://github.com/bedakb/vuewp/tree/master/public/app/themes/vuewp/app
小智 13
我建议创建一个 API 提供程序,您可以从应用程序的任何位置访问它。
只需创建一个src/utils文件夹,并在其中创建一个名为api.js.
在其中,将知道如何与 API 通信的包装器导出为对象或 ES6 静态类(如果您不害怕类,我更喜欢后者的外观和工作方式)。此提供程序可以使用您喜欢的任何 HTTP 请求库,并且您可以稍后通过更改单个文件(这个文件)而不是搜索整个代码库轻松地交换它。这是使用 axios 的示例,假设我们有一个api.example.com/v1使用 SSL的 REST API :
import axios from 'axios'
import { isProduction, env } from '@/utils/env'
const http = null // not possible to create a private property in JavaScript, so we move it outside of the class, so that it's only accessible within this module
class APIProvider {
constructor ({ url }) {
http = axios.create({
baseURL: url,
headers: { 'Content-Type': 'application/json' }
})
}
login (token) {
http.defaults.headers.common.Authorization = `Bearer ${token}`
}
logout () {
http.defaults.headers.common.Authorization = ''
}
// REST Methods
find ({ resource, query }) {
return http.get(resource, {
params: query
})
}
get ({ resource, id, query }) {
return http.get(`${resource}/${id}`, {
params: query
})
}
create ({ resource, data, query }) {
return http.post(resource, data, {
params: query
})
}
update ({ resource, id, data, query }) {
return http.patch(`${resource}/${id}`, data, {
params: query
})
}
destroy ({ resource, id }) {
return http.delete(`${resource}/${id}`)
}
}
export default new APIProvider({
url: env('API_URL') // We assume 'https://api.example.com/v1' is set as the env variable
})
Run Code Online (Sandbox Code Playgroud)
接下来,在您的main.js文件或其他任何引导 Vue 应用程序的地方,执行以下操作:
import api from '@/src/utils/api'
Vue.$api = api
Object.defineProperty(Vue.prototype, '$api', {
get () {
return api
}
})
Run Code Online (Sandbox Code Playgroud)
现在,您可以在 Vue 应用程序的任何位置以及导入 Vue 本身的任何位置访问它:
<template>
<div class="my-component">My Component</div
</template>
<script>
export default {
name: 'MyComponent',
data () {
return {
data: []
}
},
async created () {
const response = await this.$api.find({ resource: 'tasks', query: { page: 2 } })
this.data = response.data
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
或者:
// actions.js from Vuex
import Vue from 'vue'
export async function fetchTasks ({ commit }) {
const response = await Vue.$api.find({ resource: 'tasks', query: { page: 2 } })
commit('SAVE_TASKS', response.data)
return response
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
32114 次 |
| 最近记录: |