天天看點

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)
  • 本文完整代碼