npm install
npm install --save vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-cache-inmemory graphql-tag
webpack.json
包清單"dependencies": { "apollo-cache-inmemory": "^1.2.0", "apollo-client": "^2.3.0", "apollo-link": "^1.2.2", "apollo-link-http": "^1.5.4", "element-ui": "^2.3.7", "graphql": "^0.13.2", "graphql-tag": "^2.9.2", "vue": "^2.5.2", "vue-apollo": "^3.0.0-beta.5", "vue-router": "^3.0.1" },
若是遇到代碼編譯問題,請對照我使用的包版本
webpack
配置build/webpack.base.conf.js
module: { rules: [ ... { test: /\.(graphql|gql)$/, exclude: /node_modules/, loader: 'graphql-tag/loader' } ... ] }
import
時,自動作 schema js
包裝import QUERY_USER from '@/graphql/user.graphql'
,把 QUERY_USER
打印看看config.json
配置src/utils/config.json
{ "graphqlServer": "http://127.0.0.1:7001/graphql", "tokenName": "UU_AUTH_TOKEN" }
graphqlServer
服務器地址tokenName
本地寫 localStorage
key
名稱 ,推薦你們作本地化能夠用 cookie
設置過時時間VueApollo
適配器src/apolloProvider.js
import Vue from 'vue' import {ApolloClient} from 'apollo-client' import {HttpLink} from 'apollo-link-http' import {InMemoryCache} from 'apollo-cache-inmemory' import VueApollo from 'vue-apollo' import { ApolloLink, concat, split } from 'apollo-link'; import { getMainDefinition } from 'apollo-utilities'; import Config from '@/utils/config.json' Vue.use(VueApollo) const httpLink = new HttpLink({ uri: Config.graphqlServer, }) const authMiddleware = new ApolloLink((operation, forward) => { const token = localStorage.getItem(Config.tokenName) || null operation.setContext({ headers: { Authorization: `Bearer ${token}` } }); return forward(operation); }) const apolloClient = new ApolloClient({ link: concat(authMiddleware, httpLink), cache: new InMemoryCache(), connectToDevTools: true, }) const apolloProvider = new VueApollo({ defaultClient: apolloClient, defaultOptions: { $loadingKey: 'loading' }, errorHandler (error) { console.log('Global apollo error handler') console.error(error) } }) export default apolloProvider
authMiddleware
中寫入Request headers token
apolloClient
中定義cache: new InMemoryCache()
src/main.js
import apolloProvider from './apolloProvider' ... new Vue({ el: '#app', provide: apolloProvider.provide(), ... })
schema
定義src/graphql
下,有點像 restful
的 api
定義. ├── removeUser.graphql ├── user.graphql └── users.graphql
Graphql
請求src/components/HelloWorld.vue
readme.md
中只寫了一種 組件
方式調用,我仍是喜歡 api
方式組件
方式apollo: { login: { query: gql` query queryFun($username: String!, $password: String!) { user(username: $username, password: $password) { id name token } } `, variables() { return { username: 'ducafecat', password: '345457yftgyhdsfghre' } }, manual: true, result({data, loading}) { console.log(data, loading) if (!loading) { this.res = data } } } } } </script>
這種方式作查詢,適合功能單一的展現組件,靈活性感受仍是差了點,有興趣的能夠去掉註釋你們體會下。vue
api
方式query
查詢import QUERY_USER from '@/graphql/user.graphql' ... methods: { handleLogin() { this.clearData() this.$apollo .query({ // Query query: QUERY_USER, variables: { username: 'ducafecat', password: '12321321321321432' }, }) .then(response => { this.loading = false this.res = response.data localStorage.setItem(Config.tokenName, this.res.user.token) alert('登陸成功,寫入Token完成,從新裝載 apolloProvider') window.location.reload() }) .catch(error => { this.loading = false this.err = error }) },
mutate
更新handleRemoveUser() { this.clearData() this.$apollo .mutate({ // Query mutation: MUTATION_REMOVE_USER, variables: { id: 123 } }) .then(response => { this.loading = false this.res = response.data }) .catch(error => { this.loading = false this.err = error }) },