-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
安装
pnpm add villus封装
src/plugins/gql.ts
import { getToken } from '~/utils/token'
import { createClient, fetch } from 'villus'
type Methods = 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'
// 此处重写fetch,请求采用UniAPP提供的uni.request
const fetchPlugin = fetch({
fetch(url, options) {
let token = getToken()
return new Promise((resolve, reject) => {
uni.request({
url: url.toString(),
method: options?.method as Methods,
data: options?.body as any,
header: {
...options?.headers,
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
success(res) {
return resolve({
ok: true,
status: res.statusCode,
headers: res.header,
text: async () => JSON.stringify(res.data),
json: async () => res.data,
} as Response)
},
fail(e) {
return reject(e)
},
})
})
},
})
export const apolloClient = createClient({
url: 'http://localhost:4001/graphql',
use: [fetchPlugin],
})main.ts
import { apolloClient } from './plugins/gql'
export function createApp() {
const app = createSSRApp(App)
app.use(apolloClient)
return {
app,
}
}使用:
<div v-if="isFetching">Loading...</div>
<div v-else-if="error">
oh no ...{{ error }}
</div>
<div v-else>
{{ data }}
</div>
</div>
<script lang="ts" setup>
import { useQuery } from 'villus'
const { data, isFetching, error } = useQuery({
query: FindManyActorDocument,
})
</script>参考文章
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels