vue3.x中apollo的使用案例代碼
目錄
- 通過客戶端獲取Apollo配置
- 環境
- 工具的安裝
- 獲取Apollo配置
- 相關代碼
- 錯誤提示
- 通過開放接口獲取Apollo配置
- 通過不帶緩存的Http接口從Apollo讀取配置
- 參數說明
- 瀏覽器方式
- 請求交互方式
目前為止,前端獲取動態數據,都是前端與服務端進行交互獲取數據,但是如果只是獲取簡單的一些配置屬性,并沒有其它的接口需要服務端提供,此時在搭建一個服務器就是資源的浪費了,希望可以直接從 apollo的配置服務器中獲取,無需額外的服務端接口
通過前端自身直接獲取到apollo的配置目前看到官方支持的客戶端是沒有vue的,所以以下是前端獲取到apollo數據的過程
通過客戶端獲取Apollo配置
環境
"vue": "^3.2.41", "@vue/cli-service": "~5.0.8",
工具的安裝
"@vue/apollo-composable": "^4.0.0-beta.2", "@vue/apollo-option": "^4.0.0-beta.2", "graphql": "^16.6.0", "graphql-tag": "^2.12.6",
獲取Apollo配置
相關代碼
main.ts 配置建立鏈接
const httpLink = createHttpLink({
// You should use an absolute URL here
uri: apiApollo,
// credentials: "include"
})
// Cache implementation
const cache = new InMemoryCache()
// Create the apollo client
const apolloClient = new ApolloClient({
link: httpLink,
cache,
})
const apolloProvider = createApolloProvider({
defaultClient: apolloClient,
})
const app = createApp(App, {
setup() {
provide(DefaultApolloClient, apolloClient)
}
});
獲取數據
import { useQuery } from "@vue/apollo-composable";
import gql from "graphql-tag";
export default defineComponent({
name:"page-info",
setup(){
const { result, error, onResult, onError } = useQuery(gql`
query getPartners {
partners {
label,
value
}
}
`)
onResult(queryResult => {
console.log("queryResultqueryResult", queryResult.data)
console.log(queryResult.loading)
console.log(queryResult.networkStatus)
})
onError(error => {
console.log("queryResultqueryResult error", error.graphQLErrors)
console.log(error.networkError)
})
}
})
錯誤提示
Use the @apollo/client/core import path otherwise you will also import React.
一定注意引入的位置是import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client/core";而不是@apollo/client,否則就會報引入react錯誤
Uncaught (in promise) Error: Apollo client with id default not found. Use provideApolloClient() if you are outside of a component setup
該方式嘗試多種方式都是提示該錯誤,并且vue3.x 該方式暫時還沒有比較完整的文檔說明,所以該方式等以后更成熟之后在考慮
通過開放接口獲取Apollo配置
根據目前的環境使用客戶端的方式獲取Apollo配置失敗,發現目前官方推薦的還有一種方式便是通過接口獲取
通過不帶緩存的Http接口從Apollo讀取配置
接口URL格式: {config_server_url}/configs/{appId}/{clusterName}/{namespaceName}?releaseKey={releaseKey}&ip={clientIp}
Method方式: GET
參數說明
config_server_url:不是配置的UI界面的DNS,是服務器的DNS,并且兩者沒有關聯,所以如果直接拿界面的DNS獲取是獲取不到數據的
瀏覽器方式
https://apollo-config.uat.XXXX/configs/項目ID/項目空間/application
返回數據:
{
"appId": "xxxx",
"cluster": "default",
"namespaceName": "application",
"configurations": {//application 所有配置的值
"title": "Apollo set value"
},
"releaseKey": "2023021"
}
請求交互方式
axios({
method:"get",
url:"/configs/{appId}/{clusterName}/{namespaceName}"
}).then((res:any)=>{
console.log(res)
})
交互訪問也會返回相同的數據
到此這篇關于vue3.x中apollo的使用的文章就介紹到這了,更多相關vue apollo使用內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!

網公網安備