📖这次是很长时间没有看graphql这一块了,可能下个项目就要用到,emm,回顾一下。。
服务端
Install
npm init --y
npm install apollo-server-express express graphql mongoose
需要的安装目录如下
├── graphql
│ ├── resolver.js
│ └── schema.js
├── models
│ └── product.js
├── mode-modules
├── app.js
├── package-lock.json
└── package.json
各模块代码
-
graphql/shcema.js
const { gql } = require('apollo-server-express'); module.exports = gql ` type Product{ _id:Int, name:String, active:Boolean } type Query { product: [Product], getProduct(_id: Int): Product } type Mutation{ createProduct(input:ProductInput):Product } input ProductInput{ _id: Int, name:String, active:Boolean } `
-
graphql/resolver.js
var mongoose = require('mongoose'); var Product = require('../models/product') mongoose.connect('mongodb://127.0.0.1:27018/test', { useNewUrlParser: true, useUnifiedTopology: true }) mongoose.connection.on('connected', function () { console.log('连接成功'); }) mongoose.connection.on('error', function () { console.log('出错了'); }) mongoose.connection.on('disconnected', function () { console.log('连接断开'); }) var root = { Query: { product() { return Product.find({}) }, getProduct(_, args){ return Product.findOne({ _id: args._id }) } }, Mutation: { createProduct(_, { input }) { var newList = { _id: input._id, name: input.name, active: input.active } new Product(newList).save() return newList }, } } module.exports = root;
-
models/product.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ProductSchema = new Schema({ "_id": Number, "name": String, "active": Boolean }) module.exports = mongoose.model("Product", ProductSchema)
-
app.js
var {ApolloServer} = require('apollo-server-express'); const typeDefs = require('./graphql/schema'); const resolvers = require('./graphql/resolver'); const express = require('express') const app = express(); const server = new ApolloServer({ typeDefs, resolvers, playground:{ endpoint:`/graphql`, settings:{ "editor.theme":"light" } } }); const port = 9000; server.applyMiddleware({app}); app.listen({port}, () => console.log(`Server ready at http://localhost:${port}`) );
运行
node app.js
客户端
更新vue
刚才查了下我本地的vue版本是2.9.4,所以我准备先对我本地的vue升个级
npm install -g @vue/cli
这一顿操作猛如虎啊,一下就给升级到了@vue/cli 4.4.6
了。。也不知道这中间错过了些什么🧐
完了之后在终端创建vue项目,现在是直接vue create xxx
然后会出现一些选项。。来看看
一个vue项目就创建好了
Vue中GraphQL的使用(vue-apollo)
- 安装模块
npm install vue-apollo graphql apollo-boost --save
-
src/main.js
- 引入apollo-boost模块并实例化
import ApolloClient from 'apollo-boost' const apolloClient = new ApolloClient({ uri: 'http://localhost:9000/graphql' });
- 配置 vue-apollo 插件
import VueApollo from 'vue-apollo' Vue.use(VueApollo);
- 创建 Apollo provider
const apolloProvider = new VueApollo({ defaultClient: apolloClient, })
- 将apolloProvider 挂载到vue
new Vue({ apolloProvider, router, render: h => h(App) }).$mount('#app')
src/main.js完整代码
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ApolloClient from 'apollo-boost'
const apolloClient = new ApolloClient({
uri: 'http://localhost:9000/graphql'
});
import VueApollo from 'vue-apollo'
Vue.use(VueApollo);
const apolloProvider = new VueApollo({
defaultClient: apolloClient,
})
Vue.config.productionTip = false
new Vue({
apolloProvider,
router,
render: h => h(App)
}).$mount('#app')
使用vue-apollo进行查询
简单查询
<template>
<div class="hello">
无参查询
<h3 v-for="i of product" :key="i.id">{{ i.name }}</h3>
</div>
</template>
<script>
// 引入模块
import gql from "graphql-tag";
export default {
name: "HelloWorld",
props: {
msg: String
},
// 下面两个方法都可以
// apollo为默认选项
// apollo: {
// 接口名称,需要与服务端对应
// product() {
// return {
// query: gql`
// query {
// product {
// name
// }
// }
// `
// };
// }
// }
apollo: {
// 接口名称,需要与服务端对应
product: gql`
{
product {
name
}
}
`
}
};
</script>
<style scoped lang="scss">
</style>
带参查询
<template>
<div>
<button @click="getInfo()">带参查询</button>
<h3 v-for="(item,key) of productInfo" :key="key">
{{item.name}}
</h3>
</div>
</template>
<script>
import gql from "graphql-tag";
// 定义查询语句
var productGql = gql`
query getProduct($_id: Int!) {
getProduct(_id: $_id) {
name
active
}
}
`;
export default {
data() {
return {
productInfo: []
};
},
methods: {
getInfo() {
this.$apollo
.query({
query: productGql,
variables: { _id: 1002 }
})
.then(res => {
this.productInfo = res.data;
});
}
}
};
</script>
<style lang="scss" scoped>
</style>