快捷搜索: 王者荣耀 脱发

vue-apollo的使用--vue项目中使用graphql(详细版)

在前段时间使用graphql获取数据,感觉获取数据来说是方便了一些,但是也爆出了一系列的问题。先来graphql的使用方法…

  1. 下载依赖包 需要搭配Apollo一起使用
npm install -S apollo-cache-inmemory apollo-client apollo-link apollo-link-context apollo-link-http
  1. 配置(main.js中进行配置)

(1)先引入依赖包

import {ApolloClient} from apollo-client
import {HttpLink} from apollo-link-http
import {InMemoryCache} from apollo-cache-inmemory
import VueApollo from vue-apollo
import {ApolloLink} from apollo-link

(2)配置请求路径

const apiLink = new HttpLink({
  uri: http://127.0.0.1:8080/v2/api    //请求路径
})

(3)中间件添加请求头(如果不需要略掉这一步)

const middlewareLink = new ApolloLink((operation, forward) => {
  const token = sessionStorage.getItem(access_token)
  operation.setContext({
    headers: {
      Authorization: `Bearer ${token}` || null
    }
  })
  return forward(operation)
})

(4)创建Apollo连接

const apiClient = new ApolloClient({
  link: middlewareLink.concat(apiLink),  //如果不添加请求头直接放路径
  cache: new InMemoryCache()
})

(5)如果需要使用两个路径,例如一个添加请求头,一个不需要加

const apolloProvider = new VueApollo({
  clients: {
    api: apiClient,   //需要添加请求头
    base: baseClient   //不需要添加请求头
  },
  defaultClient: baseClient  //默认请求路径,如果只有一个请求就使用这个就行
})

(6)在vue中引入

Vue.use(VueApollo)
new Vue({
  el: #app,
  router,
  provide: apolloProvider.provide()  //需要添加这个
})

以上配置算是可以了


  1. 观察后台数据格式 例如格式是这样的
type APIQuery {
  workorder(code: String!): WorkOrder!
}
type WorkOrder {
  id: Int!
  code: String!
  status: Int!
  shipto: String!
  quantity: Int!
  product: Product!    //带二级数据,需要查询二级
  choices: [choicesItem!]!  //二级数组
  logistics: String!
  notes: String!
  images: String!
  created_at: String!
  updated_at: String!
}

type choicesItem{
  name: String!
  quantity: Int!
  level: Int!
  size: String!
  attributes: String!
}
  1. 在apollo.js里写前台语法 前端graphql可以这样写
import gql from graphql-tag  //引入graphql
export default apollo = {
	workorder: gql `query APIQuery($code: String!){  //如果类型后面带!表示该参数必填
    workorder(code:$code){
      code
      status
      created_at
      updated_at
      quantity
	  product {
	   code
	   name
	   price
	  }
      choices {   //二级查询,带[]
        name
        quantity
        size
        attributes
      }
    }
  }`
}

5.xx.vue文件中引入语法

import gql from ../apollo
this.$apollo
 .query({
   query: gql.workorder,
   variables: {
     code: this.$route.params.code
   },
   client: api      //如果请求不同的路径用client标识选的路径
 })
 .then(response => {
   
 })
 .catch(error => {
   
 })

至此graphql能运行起来了,开头说爆出的问题: 1、apollo返回的数据只读,不可更改,原来是想添加一个属性的。 报错: 解决的话可以把对象先转化为字符串再转化成对象,即: let a=JSON.parse(JSON.stringfy(a))

经验分享 程序员 微信小程序 职场和发展