COVID-19 自己検出システムの Web デザインおよび開発ドキュメント
Vue.js をベースにした Sylvan Ding の最初のプロジェクト。このプロジェクトで提供される情報は参照のみを目的としており、情報の正確性、有効性、適時性、完全性は保証されません。詳細については、国家衛生健康委員会委員会を参照してください。 Webサイト!
ドキュメントを参照する »
デモを表示する·バグを報告する·機能をリクエストする
Vue プロジェクトは Axios をカプセル化します
開発プロセス中、プロジェクトでの使用を容易にするために、Axios をさらにカプセル化する必要があります。これにより、コードの重複が削減される傾向があります。
開発環境
ノード | 14.16.1 |
---|---|
npm | 8.18.0 |
ビュー-cli | 2.9.6 |
ビュー | 2.5.2 |
解決
グローバル Axios が汚染され、1 つのリクエストが変更されたときに他のリクエストに影響を与えることを避けるために、src/utils/requests.js
カスタム構成を使用して axios の新しいインスタンスを作成します。環境に応じて異なるベース URL を切り替えることができます。static/mock/*.json
また、開発環境で Axios によって使用されるすべての JSON モックは、Web の元のファイル構造を維持する目的で組み込まれており、 でアクセスできるようになりますhttp://localhost:8080/static/mock/*.json
。
Axios を使用してデータを取得し、Element UI コンポーネントにロードする場合、 Vue メソッドでrequest.js
関数をインポートして作成しloadData()
、フック関数でこのメソッドを呼び出しますmounted()
。
<script>
import request from '@/utils/request'
export default {
data() {
return {
tableData: [],
}
},
mounted() {
this.loadData()
},
methods: {
loadData() {
request.get('/to/mock/file.json').then((response) => {
this.tableData = response.data
})
},
},
}
</script>
src/utils/requests.js
:
import {
errorMsg } from '@/utils/msgsettings.js'
const axios = require('axios')
const qs = require('qs')
const prodBaseURL = 'http://localhost:5000'
let axiosConfig = {
timeout: 3000,
// `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
// FormData or Stream
// You may modify the headers object.
transformRequest: [
function(data, headers) {
// Do whatever you want to transform the data
headers['content-type'] = 'application/x-www-form-urlencoded'
data = qs.stringify(data)
return data
},
],
}
// set baseURL under production environment
if (process.env.NODE_ENV === 'production') {
axiosConfig.baseURL = prodBaseURL
}
const instance = axios.create(axiosConfig)
// Add a request interceptor
instance.interceptors.request.use(
function(config) {
// Do something before request is sent
return config
},
function(error) {
// Do something with request error
errorMsg(error)
return Promise.reject(error)
}
)
// Add a response interceptor
instance.interceptors.response.use(
function(response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
console.log(response)
return response
},
function(error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
errorMsg(error)
console.log(error)
return Promise.reject(error)
}
)
export default instance
転載の際は出典を明記してください: ©️ Sylvan Ding 2022