说明 本文中 vue+node 均基于的 apollo.js 使用 vue 是在apollo基础上 封装了一个 vue的组件 方便使用
vue 使用 graphql
1 下载依赖包
npm install --save vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-cache-inmemory graphql-tag
2 以 vue 脚手架 项目结构为例
一
在 src/views/mains 里进行配置
import VueApollo from 'vue-apollo'
Vue.use(VueApollo)
然后 引入自己一会 要写的 vueApollo的二次封装的配置文件
import apolloProvider from './vueApollo'
然后 最后 new Vue时 引入他
new Vue({
el: '#app',
provide: apolloProvider.provide(),
router,
store,
i18n,
render: h => h(App)
})
二
然后相对路径 创建 vueApollo.js
内部代码如下
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import VueApollo from 'vue-apollo'
const httpLink = new HttpLink({
uri: '/v1/graphql',
/* 其中./v1是我在vue的config中配置时解决跨域时起的代理一个名字,后面的是后端
暴露接口方法的地址 */
credentials: 'same-origin'
/* 这个属性的意思是在同源的情况下携带cookie,因为vue-apollo本身发送的是一个fetch请求,所以在发送请求时不会自动携带cookie,所以我们需要加上此属性 */
})
const apolloClient = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
connectToDevTools: true
})
export default new VueApollo({
defaultClient: apolloClient,
clients: { default: apolloClient }
})
3 使用 vue-apollo
先看结构图
下面是vue页面的全部代码
<template>
<div class="app-container documentation-container" style="overflow: auto;-webkit-overflow-scrolling: touch; height: calc(100vh - 84px);">
<h1>查询</h1>
<div class="divItem">
<button @click="getInfo"> query Test 获取数据</button>
<span style="margin-left: 50px">结果:<span style="color: red">{{test1Res}}</span></span>
</div>
<div class="divItem">
<button @click="getInfo2"> query login 用户名密码 获取数据</button>
<span style="margin-left: 50px">结果:<span style="color: red">{{test2Res}}</span></span>
</div>
<div class="divItem">
<button @click="getInfo3"> query login 模型 获取数据</button>
<span style="margin-left: 50px">结果:<span style="color: red">{{test3Res}}</span></span>
</div>
<div class="divItem">
<span>输入id</span><input type="text" v-model="userId">
<button @click="getInfo4"> query getUserInfo 获取数据</button>
<span style="margin-left: 50px">结果:<span style="color: red">{{test4Res}}</span></span>
</div>
<div class="divItem">
<span>输入id</span><input type="text" v-model="userId">
<span>输入vip</span><input type="text" v-model="vip">
<button @click="getInfo5"> query getUserShowVip 获取数据</button>
<span style="margin-left: 50px">结果:<span style="color: red">{{test5Res}}</span></span>
</div>
<div class="divItem">
<span>输入vip</span><input type="text" v-model="vip">
<button @click="getInfo6"> query queryUsers 获取数据</button>
<span style="margin-left: 50px">结果:<span style="color: red">{{test6Res}}</span></span>
</div>
<div style="border-bottom: 1px solid red"></div>
<h3>修改</h3>
<div class="divItem">
<span>输入name</span><input type="text" v-model="username">
<span>输入头像</span><input type="text" v-model="userAvatar">
<span>输入vip</span><input type="text" v-model="vip">
<button @click="getInfo7"> mutation 添加数据</button>
<span style="margin-left: 50px">结果:<span style="color: red">{{test7Res}}</span></span>
</div>
</div>
</template>
<script>
import test1 from './gql/test1'
import test2 from './gql/test2'
export default {
name: 'Documentation',
data() {
return {
test1Res: '',
test2Res: '',
test3Res: '',
userId: '',
test4Res: '',
vip: '',
test5Res: '',
test6Res: '',
username: '',
userAvatar: '',
test7Res: ''
}
},
created: function() {
},
methods: {
getInfo() {
this.$apollo.query({
query: test1.testQuery
}).then((res) => {
const { test } = res.data
this.test1Res = test
})
},
getInfo2() {
const variables = {
username: 'gq',
pwd: '123'
}
this.$apollo.query({
query: test1.testLogin,
variables
}).then((res) => {
const { login } = res.data
this.test2Res = login
})
},
getInfo3() {
const variables = {
loginModel: {
username: 'gq',
pwd: '123',
authCode: '321'
}
}
this.$apollo.query({
query: test1.testLogin_m,
variables
}).then((res) => {
const { login_m } = res.data
this.test3Res = login_m
})
},
getInfo4() {
const variables = {
userid: this.userId
}
this.$apollo.query({
query: test1.getUserInfo,
variables
}).then((res) => {
const { getUserInfo } = res.data
this.test4Res = getUserInfo
})
},
getInfo5() {
const variables = {
userid: this.userId,
vip: parseInt(this.vip)
}
this.$apollo.query({
query: test1.getUserShowVip,
variables
}).then((res) => {
const { getUserShowVip } = res.data
this.test5Res = getUserShowVip
})
},
getInfo6() {
const variables = {
vip: parseInt(this.vip)
}
this.$apollo.query({
query: test1.queryUsers,
variables
}).then((res) => {
const { queryUsers } = res.data
this.test6Res = queryUsers
})
},
getInfo7() {
const variables = {
vip: parseInt(this.vip),
name: this.username,
userAvatar: this.userAvatar
}
this.$apollo.mutate({
mutation: test2.testCreateUser,
variables
}).then((res) => {
const { createUser } = res.data
this.test7Res = createUser
})
}
}
}
</script>
<style lang="scss" scoped>
.divItem{
margin-top: 30px;
}
.documentation-container {
background-color: #F9FAFB;
.document-btn {
float: left;
margin-left: 50px;
display: block;
cursor: pointer;
background: black;
color: white;
height: 60px;
width: 200px;
line-height: 60px;
font-size: 20px;
text-align: center;
}
/deep/.md-bill-detail{
padding-bottom: 0!important;
}
/deep/.md-detail-item{
font-size: 14px!important;
padding-top: 3px!important;
padding-bottom: 3px!important;
}
/deep/.md-example-child header:nth-child(2){
display: none!important;
}
/deep/.md-bill-neck{
margin: 0 24px;
}
.md-bill{
background-color: #ffffff;
}
/deep/.md-bill-header{
padding: 28px 32px 0;
}
.m20{
margin-top: 20px;
}
/* .md-water-mark{
overflow: visible;
.md-bill-neck :before,:after{
content: '';
position: absolute;
top: 0;
width: 36px;
height: 36px;
border-radius: 18px;
background-color: #F3F4F5;
}}*/
/deep/.md-bill-neck :before{
content: '';
position: absolute;
top: -11px;
width: 22px;
height: 22px;
border-radius: 11px;
background-color: #F3F4F5;
left: -44px;
}
/deep/.md-bill-neck :after{
content: '';
position: absolute;
top: -11px;
width: 22px;
height: 22px;
border-radius: 11px;
background-color: #F3F4F5;
right: -44px;
}
/deep/ .md-example-child{
margin-bottom: 20px;
}
}
</style>
上面代码中 调用方法是
this.$apollo.query 和 this.$apollo.mutate
而我们标准的 gql语言 在 相对的2个文件夹里
展示一个看看 这里要引入 graphql-tag 然后用gql 报过我们的语句即可 剩下的就是配合后台的 gql了
下面是test1
import gql from 'graphql-tag' // 引入graphql
export default {
testQuery: gql `query Query{
test
}`,
testLogin: gql `query login($username:String!,$pwd:String!){
login(username:$username,pwd:$pwd){
status
errorCode
msg
}
}`,
testLogin_m: gql `query testLogin_m($loginModel: LoginModel!){
login_m(loginModel:$loginModel){
status
errorCode
msg
}
}`,
getUserInfo: gql `query getUserInfo($userid: ID!){
getUserInfo(userid:$userid){
id
name
userAvatar
vip
showVip
token
fans {
name
}
}
}`,
getUserShowVip: gql `query ($userid: ID!,$vip:Int){
getUserShowVip(userid:$userid,vip:$vip){
id
name
userAvatar
vip
showVip
token
fans {
name
}
}
}`,
queryUsers: gql `query queryUsers($vip:Int!){
queryUsers(vip:$vip){
name
fans {
name
vip
token
}
}
}`
}
把 test2 也奉上
import gql from 'graphql-tag'
export default {
testCreateUser: gql`mutation createUser($name:String,$userAvatar:String,$vip:Int){
createUser(name:$name,userAvatar:$userAvatar,vip:$vip){
errorCode
status
msg
}
}`
}
================================分割线=========================================
下面说一下 node端 如何是用 apollo 我用的是egg框架
1 下载依赖
npm install -S apollo-boost node-fetch graphql-tag
直接在controller 的base里 引入
// import ApolloClient from 'apollo-boost';
const Apollo = require('apollo-boost')
const fetch = require('node-fetch')
// import { HttpLink } from 'apollo-link-http';
// import { InMemoryCache } from 'apollo-cache-inmemory';
const httpLink = new Apollo.HttpLink({
uri: 'http://192.168.50.82:7002/graphql',
fetch:fetch,
/* 其中./v1是我在vue的config中配置时解决跨域时起的代理一个名字,后面的是后端
暴露接口方法的地址 */
credentials: 'same-origin',
/* 这个属性的意思是在同源的情况下携带cookie,因为vue-apollo本身发送的是一个fetch请求,所以在发送请求时不会自动携带cookie,所以我们需要加上此属性 */
});
const apolloClient = new Apollo.ApolloClient({
link: httpLink,
cache: new Apollo.InMemoryCache(),
connectToDevTools: true,
});
注释的部分 是楼主第一次尝试的时候写的 后来就引入 这2个就够了
然后定义2个 base方法 一个query 一个 mutation
async gqlQuery(config) {
const res = await apolloClient.query(config)
return res.data
}
async gqlMutation(config) {
const res = await apolloClient.mutate(config)
return res.data
}
然后 引入 gql
const gql = require('graphql-tag')
//获取首页数据
// console.info('*************11111111***************')
// const testQuery = gql `query Query{
// test
// }`
// const r1 = await this.gqlQuery({
// query:testQuery
// })
// console.info(r1)
// console.info('*************22222222***************')
// console.info('*************11111111***************')
// const testLogin = gql `query login($username:String!,$pwd:String!){
// login(username:$username,pwd:$pwd){
// status
// errorCode
// msg
// }
// }`
// const variables = {
// username:'gq',
// pwd:'123'
// }
// const r1 = await this.gqlQuery({
// query:testLogin,
// variables
// })
// console.info(r1)
// console.info('*************22222222***************')
const testCreateUser = gql`mutation createUser($name:String,$userAvatar:String,$vip:Int){
createUser(name:$name,userAvatar:$userAvatar,vip:$vip){
errorCode
status
msg
}
}`
const variables = {
vip:1,
name:'1',
userAvatar:'1',
}
const r3 = await this.gqlMutation({
mutation: testCreateUser,
variables
})
大功告成 完结