vue中對接Graphql接口的實現(xiàn)示例
說明: 本文是本人正在搞nestjs+graphql+serverless訓練營中對Graphql講解的基礎知識點,可能有點前后沒對接上,文中提到的Graphql授權也是下小節(jié)介紹的
一、對原來的Express返回Graphql項目修改
本章節(jié)使用的代碼是express返回Graphql的代碼,在使用前要先對代碼進行基本的配置,比如處理跨域問題(Graphql本質(zhì)也是發(fā)送一個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 }));
二、在vue中集成Graphql
1、參考文檔地址
2、安裝依賴包
npm install --save vue-apollo graphql apollo-boost graphql-tag
3、在 src/main.js中引入 apollo-boost模塊并實例化 ApolloClient
import ApolloClient from 'apollo-boost' ... const apolloClient = new ApolloClient({ // 你需要在這里使用絕對路徑,這里就不區(qū)分環(huán)境開發(fā)了 uri: 'http://localhost:8000/graphql', }); ...
4、在 src/main.js 配置 vue-apollo 插件
import VueApollo from 'vue-apollo' Vue.use(VueApollo);
5、創(chuàng)建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')
三、查詢數(shù)據(jù)
1、使用apollo頁面進來就查詢數(shù)據(jù)
根據(jù)官方的介紹,只用將apolloProvider掛載到了vue中,在vue的鉤子函數(shù)中就會多一個屬性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中使用函數(shù)來調(diào)用
import gql from 'graphql-tag'; export default { apollo: { accountList () { return { query: gql`query { accountList{ id username password created_at } }`, } }, } }
3、點擊按鈕獲取數(shù)據(jù)
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); } }) } } }
上面的方式也可以換成下面的寫法,如果請求的業(yè)務不復雜可以這樣寫,如果復雜就根據(jù)上面的方式單獨抽取一個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、傳遞參數(shù)的方式請求數(shù)據(jù)
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('查詢單條數(shù)據(jù)', response.data); } }) }
四、對查詢數(shù)據(jù)方法改進
1、以上的方法可以查詢數(shù)據(jù),但是不能重復點擊按鈕,否則就會出現(xiàn)錯誤
2、改進版查詢數(shù)據(jù),直接使用query方法來查詢
getTableData () { this.$apollo.query({ query: gql`{ accountList{ id username password } }`, }).then(response => { console.log(response); const { accountList } = response.data; this.tableList =accountList; }) }
五、使用mutation添加數(shù)據(jù)
具體實現(xiàn)代碼見下面
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('請?zhí)砑訑?shù)據(jù)') return false; } }) }
六、優(yōu)化Graphql請求
1、打開瀏覽器控制臺點擊請求Graphql接口的時候你會發(fā)現(xiàn)有下面三個參數(shù)
2、如果同一個數(shù)據(jù)或者說variables的值沒變動的時候,是不會向后端發(fā)起請求的
3、opertionName是什么呢,我相信很多人會有疑問,看到下面兩個圖,我相信大家就不會疑惑了
這個操作名稱就是在你使用query或者mutation的時候的名字,這個命名可以隨意命名,一般建議和后端的API操作名保持一致。
這個操作名有什么用呢?我們觀察Graphql發(fā)送的請求都是同一個url地址,我們在傳統(tǒng)的Restful API的時候,我們做登錄鑒權或者獲取url的時候會就需要獲取當前請求的地址,對于Graphql來說,這個操作名也類似這個功能,區(qū)分是哪個API來請求的。
七、優(yōu)化代碼
在傳統(tǒng)的Restful api請求的時候,我們更傾向于在項目中創(chuàng)建一個services的文件夾來將api請求都放到一起,便于管理,很少將請求都寫到vue頁面中去的。在graphql中也可以如此操作,只是方式不一樣。
1、在項目中創(chuàng)建一個graphql的文件夾,里面存放的類似Restful api的接口請求
2、在src/graphql/accountList.graphql創(chuàng)建關于查詢的接口
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, '請求返回數(shù)據(jù)'); this.loading = loading; this.tableList = data.accountList; }, } ...
4、不出意外的話會直接報錯,因為vue不能直接識別graphql文件,我們需要使用webpack配置對應加載graphql的loader
5、在項目根目錄下創(chuàng)建一個vue.config.js配置loader
module.exports = { configureWebpack: (config) => { config.module.rules.push({ test: /\.(graphql|gql)$/, exclude: /node_modules/, loader: 'graphql-tag/loader' }) }, };
6、處理數(shù)據(jù)不刷新
上面每次新增數(shù)據(jù)、刪除數(shù)據(jù)、修改數(shù)據(jù),雖然我們調(diào)用了initTableData,但是Graphql,并沒有到后端,這是因為緩存的問題,需要在查詢的時候添加紅框圈住的字段就可以做到?jīng)]次調(diào)用的時候,重新更新數(shù)據(jù)
fetchPolicy: "no-cache",
7、本章節(jié)整體的效果圖
8、本小節(jié)的代碼代碼下載地址
到此這篇關于vue中對接Graphql接口的實現(xiàn)示例的文章就介紹到這了,更多相關vue對接Graphql接口 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
一個vue組件庫發(fā)布到npm的完整實現(xiàn)過程
工作的時候總是使用別人的npm包,然而我有時心底會好奇自己如何發(fā)布一個npm包呢,什么時候自己的包能夠被很多人喜歡并使用呢,下面這篇文章主要給大家介紹了關于一個vue組件庫發(fā)布到npm的相關資料,需要的朋友可以參考下2022-03-03在Vue中實現(xiàn)Excel導出功能(數(shù)據(jù)導出)
本文分享了如何在前端導出Excel文件,強調(diào)了前端導出的即時性、便捷性、靈活性和定制化優(yōu)勢,以及減輕后端服務器負擔的特點,詳細介紹了ExcelJS和FileSaver.js兩個工具庫的使用方法和主要功能,最后通過Vue實現(xiàn)了Excel的導出功能2024-10-10