在src下創(chuàng)建plugins/fetch.js
-
fetch.js中內(nèi)容:
let baseUrl; export async function $fetch (url, options) { // credentials: 'include' 解決跨域問題 const finalOptions = Object.assign({}, { headers: { 'Content-Type': 'application/json', }, credentials: 'include', }, options) const response = await fetch(`${baseUrl}${url}`, finalOptions); if (response.ok) { const data = await response.json(); return data; } else { const message = await response.text(); const error = new Error(message); error.response = response; throw error } } export default { install(Vue, options) { // console.log('Installed!', options); baseUrl = options.baseUrl; Vue.prototype.$fetch = $fetch; } }
-
在main.js中注冊插件:
// 全局配置 import VueFetch, { $fetch } from './plugins/fetch'; Vue.use(VueFetch, { baseUrl: '/api' });
-
如何使用:
// 用法1 async login() { this.$state.user = await this.$fetch('/login', { method: 'POST', body: JSON.stringify({ username: this.username, password: this.password, }), }); this.$router.replace(this.$route.params.wantedRoute || { name: 'home' }) }, // 用法2 async created() { this.loading = true; try { this.ticket = await this.$fetch(`/ticket/${this.id}`); }catch (e) { this.error = e; } this.loading = false; },
自定義插件+自定義fetch插件
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進店門袍嬉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來境蔼,“玉大人,你說我怎么就攤上這事伺通」客粒” “怎么了?”我有些...
- 文/不壞的土叔 我叫張陵罐监,是天一觀的道長吴藻。 經(jīng)常有香客問我,道長弓柱,這世上最難降的妖魔是什么沟堡? 我笑而不...
- 正文 為了忘掉前任,我火速辦了婚禮矢空,結(jié)果婚禮上航罗,老公的妹妹穿的比我還像新娘。我一直安慰自己妇多,他們只是感情好伤哺,可當(dāng)我...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般立莉。 火紅的嫁衣襯著肌膚如雪绢彤。 梳的紋絲不亂的頭發(fā)上,一...
- 文/蒼蘭香墨 我猛地睜開眼疹启,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了蔼卡?” 一聲冷哼從身側(cè)響起喊崖,我...
- 正文 年R本政府宣布谈喳,位于F島的核電站册烈,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏婿禽。R本人自食惡果不足惜赏僧,卻給世界環(huán)境...
- 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望扭倾。 院中可真熱鬧淀零,春花似錦、人聲如沸膛壹。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至肩民,卻和暖如春唠亚,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背持痰。 一陣腳步聲響...