天天看点

graphql(四)——前端如何使用graphql(graphql+vue+vue-apollo)

一、回顾 graphql(一)

在graphql(一)中提到resolver时提出一个问题:如果Schema是菜单、 Resolver是厨房,那点餐的人是?我的答案是:

客户端

。所以本节学习graphql搭建客户端。

二、搭建客户端

搭建客户端之前先了解下

Apollo

: Apollo 是通过社区力量帮助你在应用中使用

GraphQL

的一套工具。它的 客户端 和 服务端 都非常有名。Apollo 由 Meteor 开发团队 开发和支持。好,掌握核心后我们一起来看具体步骤:

  • 安装
    npm install vue-apollo graphql apollo-boost
               
    说明:可以使用

    Apollo Boost

    (零配置) 或 直接使用

    Apollo Client

    (需要更多的配置),既然有零配置的为啥不赶紧使用呢?
  • 引入及创建

    ApolloClient

    实例
    import ApolloClient from "apollo-boost";
    import VueApollo from "vue-apollo";
    Vue.use(VueApollo);
    
    //创建ApolloClient实例
    const apolloClient = new ApolloClient({
      // 这里使用绝对路径
      uri: "http://localhost:4000/graphql"
    });
    
    //Provider 保存了可以在接下来被所有子组件使用的 Apollo 客户端实例。
    const apolloProvider = new VueApollo({
      defaultClient: apolloClient
    });
    
    //使用 apolloProvider 选项将它添加到你的应用程序
    new Vue({
      router,
      apolloProvider,
      render: h => h(App)
    }).$mount('#app')
    
               

现在已经完成了在组件中使用 Apollo 的所有准备了!

三、IDE集成

前端常使用的IDE有Visual Studio Code和Webstorm。

  • Visual Studio Code
    • 若使用 VS Code,推荐安装

      Apollo GraphQL

      扩展。
      graphql(四)——前端如何使用graphql(graphql+vue+vue-apollo)
    • 然后在 Vue 项目的根目录中创建

      vue.config.js

      文件来配置它:
      module.exports = {
        // 修改的配置
        publicPath: '/',
        lintOnSave: false,    //解决eslint报错
        // 支持 gql 文件
        chainWebpack: config => {
          config.module
            .rule("graphql")
            .test(/\.(graphql|gql)$/)
            .use("graphql-tag/loader")
            .loader("graphql-tag/loader")
            .end();
        }
      }
                 
  • Webstorm
    • 若使用 Webstorm,推荐安装

      JS GraphQL

      扩展
      graphql(四)——前端如何使用graphql(graphql+vue+vue-apollo)
    • 然后在 Vue 项目的根目录中创建

      .graphqlconfig

      文件来配置它:
      {
        "name": "Untitled GraphQL Schema",
        "schemaPath": "./path/to/schema.graphql",
        "extensions": {
          "endpoints": {
            "Default GraphQL Endpoint": {
              "url": "http://url/to/the/graphql/api",
              "headers": {
                "user-agent": "JS GraphQL"
              },
              "introspect": false
            }
          }
        }
      }
                 

四、引用graphql文件及在vue文件中使用

完成上面的步骤就可以导入

xxx.gql

文件了:

  • vue搭建的项目src下面新建文件夹(graphql)
  • 在相关vue文件中引入要使用的graphql文件
  • Query(查询)
    • getUser.gql(graphql/getUser.gql)
      { getUser {      //后端定义获取数据的方法
              name,
              age,
              id,
              status,
              msg
          }
      }
                 
    • vue文件(user.vue)

      查询数据在vue文件中的使用有2种方式,第1种是将其放在vue的钩子函数里面,第2种不在钩子函数中写,结构与vue结构不搭,所以个人推荐第1种。具体如下:

      • 方 法 一 : \color{red}{方法一:} 方法一:
        import getDataGql from "../../graphql/getUser.gql";
        
        mounted(){
        	this.getData();
        },
        methods:{
        	getData() {
              this.$apollo.query({
                  query: getDataGql,      //getDataGql是引入的graphql文件定义的变量
                  variables: {}
                })
                .then(({ data: { getUser } }) => {      //getUser是getUser.gql文件(或者说后端)中定义获取数据的方法名
                  this.desserts = getUser;
                });
            },
        }
                   
      • 方 法 二 \color{red}{方法二} 方法二
        import getDataGql from "../../graphql/getUser.gql";
        export default {
          data() {
            return {
              desserts: []
            }
          },
          apollo: {
            fetchData() {
              return {
                query: getDataGql,
                update(data) {
                  console.log(data.getUser);
                  this.desserts=data.getUser
                }
              }
            }
          }
        }
                   
  • mutation(变更)

    变更里面常用的有

    增加、修改和删除

    操作,如下:
    • 增 加 \color{red}{增加} 增加
      • createUser.gql (graphql/createUser.gql)
        mutation createUser($argsMutify:MutifyUser) {      //createUser后端定义的增加数据的方法
            createUser(argsMutify:$argsMutify){
                name,
                age,
                status,
                msg,
                id
            }
        }
                   
      • vue文件(user.vue)
        import createDataGql from "../../graphql/createUser.gql";
        methods:{
        	save() {
        	   this.$apollo.mutate({
        	     mutation: createDataGql,
        	     variables: {      //传递参数
        	       argsMutify: {
        	         name: this.editedItem.name,
        	         age: Number(this.editedItem.age)
        	       }
        	     },
        	     update: (store, { data: { createUser } }) => {
        	       if (createUser.status === "200") {
        	         this.desserts.push(createUser);
        	       }
        	     }
        	   })
        	 }
        }
                   
    • 修 改 \color{red}{修改} 修改
      • updateUser.gql(graphql/updateUser.gql)
        mutation updateUser($argsMutify:MutifyUser) {
            updateUser(argsMutify:$argsMutify){
                name,
                age,
                status,
                msg
            }
        }
                   
      • vue文件(user.vue)
        import updateDataGql from '../../graphql/updateUser.gql';
        
        this.$apollo.mutate({
          mutation: updateDataGql,
          variables: {
            argsMutify: {
              name: this.editedItem.name,
              age: Number(this.editedItem.age),
              id: this.editedItem.id
            }
          },
          update: (store, { data: { updateUser } }) => {   //store是缓存,updateUser是后端定义的编辑的方法
            if (updateUser.status === "200") {
              this.snackbar = true;
              this.titleTip = updateUser.msg;   //这2行是提示信息
              this.desserts.forEach((element, index) => {    //前端做修改
                if (element.id === this.editedItem.id)
                  this.desserts.splice(index, 1, this.editedItem);
              });
            }
          }
        });
                   
    • 删 除 \color{red}{删除} 删除
      • deleteUser.gql(graphql/deleteUser.gql)
        mutation deleteUser($id:String) {
            deleteUser(id:$id){
                name,
                age,
                id,
                status,
                msg
            }
        }
                   
      • vue文件(user.vue)
        this.$apollo.mutate({
            mutation: deleteDataGql,
            variables: {
              id: this.editedItem.id
            },
            update: (store, { data: { deleteUser } }) => {
              if (deleteUser.status === "200") {
                this.snackbar = true;
                this.titleTip = deleteUser.msg;
                this.color = "info";
                var index = this.desserts.indexOf(this.editedItem);
                this.desserts.splice(index, 1);
              } else {
                this.snackbar = true;
                this.titleTip = deleteUser.msg;
                this.color = "error";
              }
              this.close();
            }
          });
                   

五、简化

上面第四点的Query与Mutation在一个vue界面中实现增删改查时需要建立4个

.gql

文件,如下图:

graphql(四)——前端如何使用graphql(graphql+vue+vue-apollo)

如果有好多个界面中都实现增删改查,是不是要建很多

.gql文件

呢(比如2个界面都有增删改查操作,就得建立8个.gql文件)?若按上面的步骤的确是,但是还有更好的办法来解决(只需要2个文件即可)。如下图:

graphql(四)——前端如何使用graphql(graphql+vue+vue-apollo)
  • graphql文件
    • mutationGraphql.js (增 删 改)
      import gql from "graphql-tag";     //graphql-tag用于解析GraphQL查询
      //增
      const createDataGql = gql `
          mutation createUser($argsMutify:MutifyUser) {
      	    createUser(argsMutify:$argsMutify){
      	        name,
      	        age,
      	        status,
      	        msg,
      	        id
      	    }
      	}
      `;
      //改
      const updateDataGql = gql `
          mutation updateUser($argsMutify:MutifyUser) {
          updateUser(argsMutify:$argsMutify){
              name,
              age,
              status,
              msg
          }
      }
      `;
      //删
      const deleteDataGql = gql `
          mutation deleteUser($id:String) {
          deleteUser(id:$id){
              name,
              age,
              id,
              status,
              msg
          }
      }
      `;
      export {createDataGql, updateDataGql,deleteDataGql};
                 
    • queryGraphql.js(查)
      import gql from "graphql-tag";
      const getDataGql=gql`
          { getUser {
              name,
              age,
              id
          }
      }
      `
      export {getDataGql};
                 
  • vue文件(user.vue)
    //在此文件中引入上面2个文件即可,其他步骤与第四中的一样
    import {getDataGql} from '../../graphql/queryGraphql';
    import {createDataGql,updateDataGql,deleteDataGql} from "../../graphql/mutationGraphql"
               

graphql搭建客户端及前端使用

graphql

就说这么多吧,有问题欢迎指出!本文完整代码已上传到git,想了解的可以去看看,下面也有相关链接。👇👇👇

相关资料

  • Vue Apollo
  • graphql服务端搭建及连接数据库(mongoDB)
  • 本文完整代码