vue中使用GraphQL查询api

一、描述

GraphQL是用于查询api的一款工具,它可以将你所需要的参数返回给你,不需要的参数就不会返回,举个例子:

1.正常请求接口

在一般的接口请求中,后端往往会将这个接口中所查到的所有数据全部返回给前端,比如我想请求一个getUser接口,最终拿到数据

//得到返回数据
{
	data: {
		username: '张三',
		userId: '123',
		sex: '0',
		age: 18,
		phone: '135xxxxxxxx'
    }
}

如上所见,我一口气得到了这个接口中的所有数据,但是在现实应用中,我只用到了username字段和phone字段,其他的数据我都是用不到的,所以就造成了数据的冗余

2.使用graphQL查询api

回到上一个问题,我在现实应用中,只用到了getUser接口中的 username 和 phone,它却给我返回了很多不相干的参数,那我就用graphQL的方式来请求一下数据

//得到数据
{
	data: {
		username: '张三',
		phone: '135xxxxxxxx'
	}
}

叮叮,你要的全拿走,多余的不挽留~,可以看到,最终拿到的数据都是你想要的,其他无用的数据都没有返回来

二、下载插件

使用npm下载下面三款插件

npm install --save vue-apollo graphql apollo-boost graphql-tag

三、使用GraphQL

1.创建GraphQL实例

(1)在common/utils/文件夹中创建 graphql.js
在这里插入图片描述
(2)在graphql.js写入以下代码

import ApolloClient from 'apollo-boost'; //引入apollo-boost插件

//实例化apolloClient
const apolloClient = new ApolloClient({
  // 你需要在这里使用绝对路径
  uri: 'http://127.0.0.1:7001/graphql'
})

//导出实例
export default apolloClient;

【注】引入插件的时候有可能会报以下错误
在这里插入图片描述
如果发现在这个报错,在vue.config.js里面做一下配置就可以了

//vue.config.js
module.exports = {
    chainWebpack: (config) => {
        // GraphQL Loader
        config.module // optional
            .rule('graphql')
            .test(/\.graphql$/)
            .use('graphql-tag/loader')
            .loader('graphql-tag/loader')
            .end()

        config.module
            .rule('mjs')
            .test(/\.mjs$/)
            .include.add(/node_modules/)
            .end()
            .type('javascript/auto')
            .end()

        config.resolve.extensions
            .add('.mjs')
            .add('.gql')
            .add('.graphql')
            .end()
    }
}

2.编写请求方法

在 common/utils 文件夹中 创建相应的请求文件(文件名根据接口的功能取就可以)
在这里插入图片描述
下面就可以正式的编写请求方法了

//article.js
import apolloClient from './graphql'
import gql from 'graphql-tag'
//query方式的请求
export function questionById(params) {
	return apolloClient.query({
		query: gql`query ($id: ID) { //这里的$id:ID 是对请求参数的约束,常见的有String,Int,ID
           questionById(id: $id) { //后端中定义的方法名称 括号中的是请求参数
           		 id //想要拿到的参数,不传的话接口中就不会返回这个字段了
           		 title //如上
           		 content //如上
           		 userId //如上
           }
        }`,
		variables: params //变量{id: 1},query($id: Id) 中的id就是取的这里的变量
	})
}

//mutation方式的请求
export function add(params) {
	return apolloClient.mutate({
		mutation: gql`mutation($question: addUserInput!) {
			add(question:$question)
		}`,
		variables: params
	})
}

3.发起请求

(1)在你所需要请求数据的页面引入上面的请求文件

import { questionById, add } from '@/common/utils/article';

(2)发起请求

export default {
		data() {
			return {
				list: []
			}
		},
		created() {
			this.initData()
		},
		methods: {
			 initData() {
			      questionById({id: 126628556787679232})
			        .then(res=>{
			          console.info('获取数据=》'+JSON.stringify(res))
			          this.list = [res.data.questionById]
			        })
			        .catch(err=>{
			          console.log(err)
			        })
			    },
				
			   add() {
				   add({question: {title: '哈哈哈', content: '瓦蓝蓝的天空飞老鹰', userId: 1}}).then(res => {
					   console.info('添加数据=>'+ JSON.stringify(res))
					   if(res.data.add) {
						   uni.showToast({title: '添加成功'})
					   }
				   })
			   }
			
		}
	}
</script>

大功告成,来看一下请求回来的数据吧
在这里插入图片描述

在这里插入图片描述

四、其他方法

1.设置headers

const apolloClient = new ApolloClient({
  // 你需要在这里使用绝对路径
  uri: 'http://192.168.0.5:10014/graphql',
  request: operation =>
          operation.setContext(() => ({
              headers: {
                  authorization: '123'
              }
          }))
})
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
好的,下面是在 Spring Boot 使用 GraphQL 的一些指导步骤: 1. 在 pom.xml 添加 GraphQL 的依赖: ``` <dependency> <groupId>com.graphql-java</groupId> <artifactId>graphql-spring-boot-starter</artifactId> <version>5.0.2</version> </dependency> ``` 2. 创建 GraphQL 查询类型和 GraphQL 查询对象类型。例如,你可能会创建一个查询类型来表示用户的名称: ``` public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Query { private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } } ``` 3. 创建 GraphQL 查询解析器类。该类将负责解析 GraphQL 查询并返回结果。例如: ``` @Component public class GraphQLQueryResolver { private UserRepository userRepository; public GraphQLQueryResolver(UserRepository userRepository) { this.userRepository = userRepository; } public User getUser(String name) { return userRepository.findByName(name); } } ``` 4. 在 Spring Boot 应用程序启用 GraphQL。要启用 GraphQL,请在应用程序类上添加 @EnableGraphQL 注释: ``` @SpringBootApplication @EnableGraphQL public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 5. 在前端使用 Vue 查询 GraphQL API。要查询 GraphQL API,你可以使用 Vue 的 axios 库发送 HTTP 请求,例如: ``` axios.post('/graphql', { query: ` query { user(name: "John") { name } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雾里桃花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值