vue 에서 Graphql 인 터 페 이 스 를 연결 하 는 예제

설명:본 고 는 본인 이 nestjs+graphql+server less 훈련 캠프 에서 Graphql 에 대한 설명 을 하 는 기초 지식 점 입 니 다.앞 뒤 가 연결 되 지 않 았 을 수도 있 습 니 다.글 에서 언급 한 Graphql 권한 수여 도 다음 절 에 소개 합 니 다.
1.원래 의 Express 반환 Graphql 프로젝트 수정
이 장 에서 사용 하 는 코드 는 express 가 Graphql 로 돌아 가 는 코드 입 니 다.사용 하기 전에 코드 에 대해 기본 적 인 설정 을 해 야 합 니 다.예 를 들 어 크로스 필드 문 제 를 처리 해 야 합 니 다(Graphql 본질 도 http 요청 을 보 냅 니 다.이렇게 되면 vue 프로젝트 에 크로스 필드 문제 가 자 연 스 럽 게 존재 하 므 로 먼저 처리 해 야 합 니 다)
1.도 메 인 을 뛰 어 넘 는 패 키 지 를 설치 하고 미들웨어 를 설정 합 니 다.

npm install cors

const cors = require('cors');
//       
app.use(cors());

2.요청 체 를 가 져 오 는 미들웨어 설정

//     
app.use(express.json());//express.json=bodyParser.json
app.use(express.urlencoded({ extended: true }));
2.vue 에 Graphql 통합
1、 문서 주소 참조
2.의존 팩 설치

npm install --save vue-apollo graphql apollo-boost graphql-tag
3.src/main.js 에 apollo-boost 모듈 을 도입 하고 Apollo Client 를 예화 합 니 다.

import ApolloClient from 'apollo-boost'
...
const apolloClient = new ApolloClient({ 
  //             ,            
  uri: 'http://localhost:8000/graphql',
});
...
4.src/main.js 에 vue-apollo 플러그 인 설정

import VueApollo from 'vue-apollo' 
Vue.use(VueApollo);
5.Apollo provider 공급 자 를 만 들 고 응용 프로그램 에 마 운 트 합 니 다.

import Vue from 'vue'
import App from './App.vue'
import ApolloClient from 'apollo-boost'
import VueApollo from 'vue-apollo' 
Vue.use(VueApollo);

Vue.config.productionTip = false

const apolloClient = new ApolloClient({ 
  //              
  uri: 'http://localhost:8000/graphql',
});
const apolloProvider = new VueApollo({
  defaultClient: apolloClient,
})

new Vue({
  render: h => h(App),
  //      
  apolloProvider,
}).$mount('#app')

3.조회 데이터
1.apollo 페이지 로 들 어 오 면 데 이 터 를 조회 합 니 다.
공식 소개 에 따 르 면 apollo Provider 를 vue 에 마 운 트 하면 vue 의 갈고리 함수 에 속성 apollo 가 하나 더 있 습 니 다.

<template>
  <div class="about">
    {{accountList}}
  </div>
</template>


import gql from 'graphql-tag';
export default {
  name: 'About',
  apollo: {
    accountList: gql`query {
      accountList {
        id
        username
        password
      }
    }`
  },
}

2.apollo 에서 함 수 를 사용 하여 호출 합 니 다.

import gql from 'graphql-tag';
export default {
  apollo: {
    accountList () {
      return {
        query: gql`query {
          accountList{ 
            id
            username
            password
            created_at
          }
        }`,
      }
    },
  }
}
3.버튼 을 누 르 면 데이터 가 져 오기

import gql from 'graphql-tag';
//      schema
const accountListGql = gql`{
  accountList {
    id
    username
    password
  }
}`;

export default {
  data() {
    return {
      tableList: [],
    }
  },
  methods: {
    getTableData() {
      this.$apollo.addSmartQuery('accountList', {
        query: accountListGql,
        result(response) {
          console.log(response);
          const {accountList} = response.data;
          this.tableList = accountList;
        },
        error(error) {
          console.log('    ', error);
        }
      })
    }
  }
}

위의 방식 도 아래 의 쓰기 로 바 꿀 수 있 습 니 다.만약 에 요청 한 업무 가 복잡 하지 않 으 면 이렇게 쓸 수 있 습 니 다.복잡 하면 위의 방식 에 따라 schema 를 따로 추출 할 수 있 습 니 다.

...
getTableData() {
  this.$apollo.addSmartQuery('accountList', {
    query: gql`{
      accountList{
        id
        username
        password
      }
    }`,
    result(response) {
      console.log(response);
      const {accountList} = response.data;
      this.tableList = accountList;
    },
    error(error) {
      console.log('    ', error);
    }
  })
}
...
4.매개 변 수 를 전달 하 는 방식 으로 데 이 터 를 요청 합 니 다.

handleClick (rowData) {
  this.$apollo.addSmartQuery('account', {
    query: gql`
      query($id: ID!) {
        account(id: $id) {
          id
          username
          password
        }
      }
    `,
    variables: {
      id: rowData.id,
    },
    result (response) {
      console.log('      ', response.data);
    }
  })
}
4.조회 데이터 방법 개선
1.이상 의 방법 으로 데 이 터 를 조회 할 수 있 지만 버튼 을 반복 해서 누 르 면 안 됩 니 다.그렇지 않 으 면 오류 가 발생 할 수 있 습 니 다.

2.개선 판 조회 데 이 터 는 query 방법 으로 직접 조회 합 니 다.

getTableData () {
  this.$apollo.query({
    query: gql`{
      accountList{
        id
        username
        password
      }
    }`,
  }).then(response => {
    console.log(response);
    const { accountList } = response.data;
    this.tableList =accountList;
  })
}
5.mutation 으로 데이터 추가
구체 적 인 실현 코드 는 아래 와 같다.

onSubmit () {
  this.$refs.form.validate(async (valid) => {
    if (valid) {
      console.log(this.form);
      const result = await this.$apollo.mutate({
        mutation: gql`
          mutation addAccount($username: String!, $password: String!) {
            addAccount(username:$username,password: $password)
          }
        `,
        variables: {
          username: this.form.username,
          password: this.form.password,
        }
      });
      console.log('    ', result);
    } else {
      // this.$message.error('     ')
      return false;
    }
  })
}
6.최적화 Graphql 요청
1.브 라 우 저 콘 솔 을 열 고 Graphql 인 터 페 이 스 를 요청 하려 면 다음 세 개의 인자 가 있 습 니 다.

2.같은 데이터 나 variables 의 값 이 변동 되 지 않 았 을 때 백 엔 드 에 요청 하지 않 습 니 다.
3.opertionName 은 무엇 일 까요?저 는 많은 사람들 이 의문 을 가 질 것 이 라 고 믿 습 니 다.다음 두 그림 을 보면 여러분 들 이 의심 하지 않 을 것 이 라 고 믿 습 니 다.


이 작업 이름 은 query 나 mutation 을 사용 할 때의 이름 입 니 다.이 이름 은 마음대로 이름 을 지 을 수 있 습 니 다.일반적으로 백 엔 드 의 API 작업 이름과 일치 하 는 것 을 권장 합 니 다.
이 조작 명 은 무슨 소 용이 있 습 니까?Graphql 에서 보 내 는 요청 이 모두 같은 url 주 소 를 관찰 합 니 다.우 리 는 전통 적 인 Restful API 를 사용 할 때 로그 인 인증 권 을 만 들 거나 url 을 가 져 올 때 현재 요청 한 주 소 를 가 져 와 야 합 니 다.Graphql 에 있어 서 이 작업 이름 도 이 기능 과 유사 합 니 다.구역 은 어떤 API 로 요청 합 니까?
7.최적화 코드
전통 적 인 Restful api 요청 을 할 때 저 희 는 프로젝트 에서 services 폴 더 를 만들어 api 요청 을 모두 함께 놓 고 관리 하기 쉬 우 며 요청 을 vue 페이지 에 쓰 는 경향 이 있 습 니 다.graphql 에서 도 이렇게 조작 할 수 있 습 니 다.다만 방식 이 다 릅 니 다.
1.프로젝트 에 graphql 폴 더 를 만 듭 니 다.그 안에 저 장 된 Restful api 와 같은 인터페이스 요청
2.src/graphql/acountList.graphql 에서 조회 에 관 한 인 터 페 이 스 를 만 듭 니 다.

query AccountList {
  accountList {
    id
    username
    password
  }
}
3.vue 에 도입

import AccountList from './../graphql/accountList.graphql';
...
methods: {
  async initTableData () {
    this.tableList = [];
    this.loading = true;
    const { data, loading } = await this.$apollo.query({
      query: AccountList,
    });
    console.log(data, '      ');
    this.loading = loading;
    this.tableList = data.accountList;
  },
}
...
4.의외 의 사고 가 발생 하지 않 으 면 바로 오 류 를 보고 할 수 있 습 니 다.vue 는 graphql 파일 을 직접 식별 할 수 없 기 때문에 웹 팩 설정 을 사용 하여 graphql 을 불 러 오 는 loader 를 설정 해 야 합 니 다.
5.프로젝트 루트 디 렉 터 리 에 vue.config.js 설정 loader 를 만 듭 니 다.

module.exports = {
  configureWebpack: (config) => {
    config.module.rules.push({
      test: /\.(graphql|gql)$/,
      exclude: /node_modules/,
      loader: 'graphql-tag/loader'
    })
  },
};
6.처리 데이터 새로 고침 하지 않 음
위 에서 매번 데 이 터 를 추가 하고 데 이 터 를 삭제 하 며 데 이 터 를 수정 합 니 다.initTableData 를 호출 했 지만 Graphql 은 백 엔 드 에 도착 하지 않 았 습 니 다.캐 시 문제 때 문 입 니 다.검색 할 때 빨 간 상자 에 둘러싸 인 필드 를 추가 하면 호출 되 지 않 았 을 때 데 이 터 를 다시 업데이트 할 수 있 습 니 다.

fetchPolicy: "no-cache",

7.본 장의 전체적인 효과 도

8.이 소절 의 코드코드 다운로드 주소
vue 에서 Graphql 인 터 페 이 스 를 연결 하 는 예제 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 vue 도 킹 Graphql 인터페이스 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!

좋은 웹페이지 즐겨찾기