In the previous part, we used NestJS to quickly build a GraphQL API service with CRUD function. So this article will be a simple example in Vue project, how to use the GraphQL API to implement add, delete, change and query as easily as using AXIos;
Technology stack Vue + TypeScript + VUe-Apollo
Step one, create the project
-
Create the project using @vue/cli
# create project vue create vue-apollo-graphql Copy the code
The command line query asks whether to use presets:
Vue CLI v4.4.6? Please pick a preset: default (babel, eslint) > Manually select featuresSelect Manual configuration and press Enter Copy the code
It then asks us to select the feature (up and down arrow moves the option, space toggle is checked) :
Vue CLI v4.4.6? Please pick a preset: Manually select features ? Check the features neededfor your project: >(*) Babel (*) TypeScript # use ts( ) Progressive Web App (PWA) Support (*) Router ( ) Vuex ( ) CSS Pre-processors (*) Linter / Formatter ( ) Unit Testing ( ) E2E TestingCopy the code
If you want to use class style vUE components, please select Yes. The complete options are as follows:
-
Add vue-cli-plugin-Apollo plugin
vue add apollo Copy the code
After the addition, the plugin will ask us whether to add the sample code, whether to add GraphQL service, whether to configure Apollo engine. We don’t need these things here, just select N all the way.
-
Start the project
yarn yarn serve Copy the code
Second, configure Apollo-GraphQL
-
In the root directory
apollo.config.js
Used to configure VScodeApollo GraphQL
Plugin to get the server’s GraphQL type definition;The Apollo GraphQL plug-in needs to be installed in advance by VScode
module.exports = { client: { service: { name: env.VUE_APP_APOLLO_ENGINE_SERVICE, url: env.APOLLO_ENGINE_API_ENDPOINT, // GraphQL service URL skipSSLValidation: true.addTypename: false./ / localSchemaFile: '. / SRC/graphql/schema. Graphql ', / / local type definition }, includes: ['src/**/*.{js,jsx,ts,tsx,vue,gql}'],},engine: { endpoint: env.APOLLO_ENGINE_API_ENDPOINT, apiKey: env.VUE_APP_APOLLO_ENGINE_KEY, }, } Copy the code
For configuration details, see the configuration documentation on apollo-GraphQL’s website.
-
Modify the
src/vue-apollo.ts
Used to set the vue-apollo Connection configuration;// Other unchanged Settings are omitted const defaultOptions = { // Set to remove the __typename field inMemoryCacheOptions: { addTypename: false,}}Copy the code
By default, apollo-GraphQL returns data with a __typename field that determines the return type. But we don’t need it, and it would affect the use of the form, so we don’t add the __typename field
Step 3, use Apollo-GraphQL for CRUD
First we create apolloexample.vue under SRC/Components;
-
The new goods
In 1.1.
src/graphql
createaddOneGoods.gql
, for new goods:mutation addOneGoods($goods: GoodsInsertTypeGraphql!) { addOneGoods(goods: $goods) { id name price count remark } } Copy the code
The syntax of. GQL can be found in the GraphQL learning document on the official website
1.2. The introduction of
addOneGoods.gql
, the use ofthis.$apollo.mutate
Call this Mutations, add product information:import ADD_ONE_GOODS from '@/graphql/addOneGoods.gql' // Add a new item handleAddOneGoods(goods: IGoods) { this.$apollo .mutate({ mutation: ADD_ONE_GOODS, variables: { goods: goods }, }) .then(() = > { this.$message.success('New item added successfully') }) .catch(e= > { this.$notify.error('Request error:${e.message}`)})}Copy the code
IGoods are type definitions for goods:
export interfaceIGoods { id? :string name: string price: number count: number remark: string } Copy the code
-
Querying commodity list
In 2.1.
src/graphql
creategetAllGoods.gql
, used to query all goods;query getAllGoods { getAllGoods { id name price count remark } } Copy the code
In 2.2.
components/ApolloExample.vue
In the introductiongetAllGoods.gql
, the use ofthis.$apollo.query
Call this Query;import GET_ALL_GOODS from '@/graphql/getAllGoods.gql' getAllGoodsData() { this.$apollo .query({ query: GOODS }) .then(res= > { this.goodsList = res.data.getAllGoods }) .catch(e= > { this.$notify.error('Failed to get item list:${e.message}`) this.goodsList = [] }) } Copy the code
-
Update commodity information
In 3.1.
src/graphql
createupdateGoods.gql
, for updating goods;mutation updateGoods($goods: GoodsInputTypeGraphql!) { updateGoods(goods: $goods) { id name price count remark } } Copy the code
3.2. The introduction of
updateGoods.gql
, the use ofthis.$apollo.mutate
Call this Mutations, update the product information;import UPDATE_GOODS from '@/graphql/updateGoods.gql' // Update the product information handleUpdateGoods(goods: IGoods) { this.$apollo .mutate({ mutation: UPDATE_GOODS, variables: { goods: goods }, }) .then(() = > { this.$message.success('Modified product information successfully') }) .catch(e= > { this.$notify.error('Request error:${e.message}`)})}Copy the code
-
Delete the goods
In 4.1.
src/graphql
createdeleteOneGoods.gql
, used to delete goods;mutation deleteOneGoods($id: String!) { deleteOneGoods(id: $id) } Copy the code
4.2. The introduction of
deleteOneGoods.gql
, the use ofthis.$apollo.mutate
Call this Mutations, update the product information;import DELETE_ONE_GOODS from '@/graphql/deleteOneGoods.gql' // Delete an item handleDelete(goods: IGoods) { this.$apollo .mutate({ mutation: DELETE_ONE_GOODS, variables: { id: goods.id }, }) .then(() = > { this.$message.success('Deleted item succeeded') }) .catch(e= > { this.$notify.error('Request error:${e.message}`)})}Copy the code
This completes the basic CRUD operations. Finally, for demonstration purposes, let’s simply write the interface with element-UI:
To sum up:
The rough usage process is not much different from an AXIOS request
- define
.gql
The file is similar to the AXIOS definition API request; - The introduction of
.gql
The file is similar to the introduction of defining API request methods; - use
this.$apollo.query
ormutate
, similar to theaxios.get
oraxios.post
Call the interface, pass the parameters;
Hit the pit:
This.$apollo.mutate (); this.$apollo.mutate (); Examples are in the complete code;