vue中對(duì)接Graphql接口的實(shí)現(xiàn)示例
說(shuō)明: 本文是本人正在搞nestjs+graphql+serverless訓(xùn)練營(yíng)中對(duì)Graphql講解的基礎(chǔ)知識(shí)點(diǎn),可能有點(diǎn)前后沒對(duì)接上,文中提到的Graphql授權(quán)也是下小節(jié)介紹的
一、對(duì)原來(lái)的Express返回Graphql項(xiàng)目修改
本章節(jié)使用的代碼是express返回Graphql的代碼,在使用前要先對(duì)代碼進(jìn)行基本的配置,比如處理跨域問題(Graphql本質(zhì)也是發(fā)送一個(gè)http請(qǐng)求,既然是這樣在vue項(xiàng)目中自然存在跨域的問題,需要先處理)
1、安裝跨域的包,并且配置中間件
npm install cors
const cors = require('cors');
// 處理跨域請(qǐng)求
app.use(cors());
2、配置獲取請(qǐng)求體的中間件
// 處理請(qǐng)求
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模塊并實(shí)例化 ApolloClient
import ApolloClient from 'apollo-boost'
...
const apolloClient = new ApolloClient({
// 你需要在這里使用絕對(duì)路徑,這里就不區(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提供者,并且掛載到應(yīng)用中
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({
// 你需要在這里使用絕對(duì)路徑
uri: 'http://localhost:8000/graphql',
});
const apolloProvider = new VueApollo({
defaultClient: apolloClient,
})
new Vue({
render: h => h(App),
// 掛載到應(yīng)用
apolloProvider,
}).$mount('#app')
三、查詢數(shù)據(jù)
1、使用apollo頁(yè)面進(jìn)來(lái)就查詢數(shù)據(jù)
根據(jù)官方的介紹,只用將apolloProvider掛載到了vue中,在vue的鉤子函數(shù)中就會(huì)多一個(gè)屬性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ù)來(lái)調(diào)用
import gql from 'graphql-tag';
export default {
apollo: {
accountList () {
return {
query: gql`query {
accountList{
id
username
password
created_at
}
}`,
}
},
}
}
3、點(diǎn)擊按鈕獲取數(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('請(qǐng)求失敗', error);
}
})
}
}
}
上面的方式也可以換成下面的寫法,如果請(qǐng)求的業(yè)務(wù)不復(fù)雜可以這樣寫,如果復(fù)雜就根據(jù)上面的方式單獨(dú)抽取一個(gè)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('請(qǐng)求失敗', error);
}
})
}
...
4、傳遞參數(shù)的方式請(qǐng)求數(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);
}
})
}
四、對(duì)查詢數(shù)據(jù)方法改進(jìn)
1、以上的方法可以查詢數(shù)據(jù),但是不能重復(fù)點(diǎn)擊按鈕,否則就會(huì)出現(xiàn)錯(cuò)誤

2、改進(jìn)版查詢數(shù)據(jù),直接使用query方法來(lái)查詢
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ù)
具體實(shí)現(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('更新結(jié)果', result);
} else {
// this.$message.error('請(qǐng)?zhí)砑訑?shù)據(jù)')
return false;
}
})
}
六、優(yōu)化Graphql請(qǐng)求
1、打開瀏覽器控制臺(tái)點(diǎn)擊請(qǐng)求Graphql接口的時(shí)候你會(huì)發(fā)現(xiàn)有下面三個(gè)參數(shù)

2、如果同一個(gè)數(shù)據(jù)或者說(shuō)variables的值沒變動(dòng)的時(shí)候,是不會(huì)向后端發(fā)起請(qǐng)求的
3、opertionName是什么呢,我相信很多人會(huì)有疑問,看到下面兩個(gè)圖,我相信大家就不會(huì)疑惑了


這個(gè)操作名稱就是在你使用query或者mutation的時(shí)候的名字,這個(gè)命名可以隨意命名,一般建議和后端的API操作名保持一致。
這個(gè)操作名有什么用呢?我們觀察Graphql發(fā)送的請(qǐng)求都是同一個(gè)url地址,我們?cè)趥鹘y(tǒng)的Restful API的時(shí)候,我們做登錄鑒權(quán)或者獲取url的時(shí)候會(huì)就需要獲取當(dāng)前請(qǐng)求的地址,對(duì)于Graphql來(lái)說(shuō),這個(gè)操作名也類似這個(gè)功能,區(qū)分是哪個(gè)API來(lái)請(qǐng)求的。
七、優(yōu)化代碼
在傳統(tǒng)的Restful api請(qǐng)求的時(shí)候,我們更傾向于在項(xiàng)目中創(chuàng)建一個(gè)services的文件夾來(lái)將api請(qǐng)求都放到一起,便于管理,很少將請(qǐng)求都寫到vue頁(yè)面中去的。在graphql中也可以如此操作,只是方式不一樣。
1、在項(xiàng)目中創(chuàng)建一個(gè)graphql的文件夾,里面存放的類似Restful api的接口請(qǐng)求
2、在src/graphql/accountList.graphql創(chuàng)建關(guān)于查詢的接口
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, '請(qǐng)求返回?cái)?shù)據(jù)');
this.loading = loading;
this.tableList = data.accountList;
},
}
...
4、不出意外的話會(huì)直接報(bào)錯(cuò),因?yàn)関ue不能直接識(shí)別graphql文件,我們需要使用webpack配置對(duì)應(yīng)加載graphql的loader
5、在項(xiàng)目根目錄下創(chuàng)建一個(gè)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,并沒有到后端,這是因?yàn)榫彺娴膯栴},需要在查詢的時(shí)候添加紅框圈住的字段就可以做到?jīng)]次調(diào)用的時(shí)候,重新更新數(shù)據(jù)
fetchPolicy: "no-cache",

7、本章節(jié)整體的效果圖

8、本小節(jié)的代碼代碼下載地址
到此這篇關(guān)于vue中對(duì)接Graphql接口的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)vue對(duì)接Graphql接口 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue實(shí)現(xiàn)靜態(tài)頁(yè)面點(diǎn)贊和取消點(diǎn)贊功能
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)靜態(tài)頁(yè)面點(diǎn)贊和取消點(diǎn)贊的功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02
一個(gè)vue組件庫(kù)發(fā)布到npm的完整實(shí)現(xiàn)過程
工作的時(shí)候總是使用別人的npm包,然而我有時(shí)心底會(huì)好奇自己如何發(fā)布一個(gè)npm包呢,什么時(shí)候自己的包能夠被很多人喜歡并使用呢,下面這篇文章主要給大家介紹了關(guān)于一個(gè)vue組件庫(kù)發(fā)布到npm的相關(guān)資料,需要的朋友可以參考下2022-03-03
詳解基于iview-ui的導(dǎo)航欄路徑(面包屑)配置
這篇文章主要介紹了詳解基于iview-ui的導(dǎo)航欄路徑(面包屑)配置,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2019-02-02
VUE對(duì)Storage的過期時(shí)間設(shè)置,及增刪改查方式
這篇文章主要介紹了VUE對(duì)Storage的過期時(shí)間設(shè)置,及增刪改查方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
在Vue中實(shí)現(xiàn)Excel導(dǎo)出功能(數(shù)據(jù)導(dǎo)出)
本文分享了如何在前端導(dǎo)出Excel文件,強(qiáng)調(diào)了前端導(dǎo)出的即時(shí)性、便捷性、靈活性和定制化優(yōu)勢(shì),以及減輕后端服務(wù)器負(fù)擔(dān)的特點(diǎn),詳細(xì)介紹了ExcelJS和FileSaver.js兩個(gè)工具庫(kù)的使用方法和主要功能,最后通過Vue實(shí)現(xiàn)了Excel的導(dǎo)出功能2024-10-10

