总共有4种方式:
无状态服务:那么你应该使用 mixins
有状态服务:使用 Vuex
从 vue 代码导出服务和导入
任何 javascript 全局对象
我使用 axios 作为 HTTP 客户端进行 api 调用,我在我的 src
文件夹中创建了一个 gateways
文件夹,并为每个后端放置了文件,创建了 axios instances,如下所示
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'
}
})
现在在您的组件中,您可以拥有一个从 api 获取数据的函数,如下所示:
methods: {
getProducts () {
myApi.get('products?id=' + prodId).then(response => this.product = response.data)
}
}
我假设您想在多个组件中重复使用此方法,您可以使用 vue.js 的 mixins:
Mixin 是一种为 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')
}
})
我主要使用 Vue 资源。
1.我创建新文件,在其中使用 Vue.http.xxx
连接到 API 端点。假设我们有输出帖子的端点。在您的项目中创建新目录,我称之为 services
,然后创建名为 {3 } - 内容如下所示:
import Vue from 'vue'
export default {
get() {
return Vue.http.get('/api/posts)
}
}
然后我转到我想使用此服务的组件,然后将其导入
import PostsService from '../services/PostsService'
export default {
data() {
return {
items: []
}
},
created() {
this.fetchPosts()
},
methods: {
fetchPosts() {
return PostsService.get()
.then(response => {
this.items = response.data
})
}
}
}
有关此方法的更多信息,请随时查看我在 GitHub 上的存储库 https://github.com/bedakb/vuewp/tree/master/public/app/themes/vuewp/app
我建议创建一个 API Provider,您可以从应用程序的任何位置访问它。
只需创建一个 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
})
接下来,在您的 main.js
文件或您引导 Vue 应用程序的其他任何地方,执行以下操作:
import api from '@/src/utils/api'
Vue.$api = api
Object.defineProperty(Vue.prototype, '$api', {
get () {
return api
}
})
现在,您可以在 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>
或者:
// 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
}
希望这可以帮助。
.$api
部分仅供参考,在 TS 中您需要执行 (Vue.prototype as any).$api = yourobject;
。此外,有关该功能的 v2 文档在这里:vuejs.org/v2/cookbook/adding-instance-properties.html
我认为对于您的简单问题,答案可能是任何包含函数的 ES6 模块(相当于 Angular 中的类中的方法)并使用 ES6 导入和导出直接将它们导入组件中。没有可以在组件中注入的此类服务。
您可以创建自己的服务,在其中放置所有 HTTP 服务器调用,然后将其导入到要使用它们的组件中。
最好将 Vuex 用于复杂的状态管理应用程序,因为在 Vuex 中,您可以通过始终异步运行的操作来处理所有异步调用,然后在获得结果后提交突变。突变将直接与状态交互并更新它以不可变的方式(这是首选)。这是有状态的方法。
还有其他方法。但这些是我在代码中遵循的。
不定期副业成功案例分享