欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

為vue項(xiàng)目自動(dòng)設(shè)置請(qǐng)求狀態(tài)的配置方法

 更新時(shí)間:2019年06月09日 12:15:19   作者:Kim09AI  
這篇文章主要介紹了vue項(xiàng)目自動(dòng)設(shè)置請(qǐng)求狀態(tài)的配置方法,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

在進(jìn)入一個(gè)頁(yè)面的時(shí)候,一般在獲取數(shù)據(jù)的同時(shí),會(huì)先顯示一個(gè) loading ,等請(qǐng)求結(jié)束再隱藏 loading 渲染頁(yè)面,只需要用一個(gè)屬性去記錄請(qǐng)求的狀態(tài),再根據(jù)這個(gè)狀態(tài)去渲染頁(yè)面就好了

async handler() {
  this.loading = true
  await fetch()
  this.loading = false
}

雖然是很簡(jiǎn)單的功能,可是要處理的地方多的時(shí)候,還是很繁瑣的,就想著能不能統(tǒng)一設(shè)置處理請(qǐng)求的 loading ,然后頁(yè)面根據(jù) loading 的狀態(tài)決定要顯示的內(nèi)容,就根據(jù)自己的想法做了一些封裝,自動(dòng)給所有 ajax 請(qǐng)求設(shè)置 loading 狀態(tài),主要思路是把所有請(qǐng)求集中到單一實(shí)例上,通過(guò) proxy 代理屬性訪問(wèn),把 loading 狀態(tài)提交到 store 的 state 中

安裝

$ npm install vue-ajax-loading

演示

在線demo(打開(kāi)較慢)

 

使用

配置 store 的 state 及 mutations

import { loadingState, loadingMutations } from 'vue-ajax-loading'

const store = new Vuex.Store({
  state: {
    ...loadingState
  },
  mutations: {
    ...loadingMutations
  }
})

把所有請(qǐng)求集中到一個(gè)對(duì)象上

import { ajaxLoading } from 'vue-ajax-loading'
import axios from 'axios'
import store from '../store' // Vuex.Store 創(chuàng)建的實(shí)例
axios.defaults.baseURL = 'https://cnodejs.org/api/v1'
// 把請(qǐng)求集中到單一對(duì)象上,如:
const service = {
  global: {
    // 全局的請(qǐng)求
    getTopics() {
      return axios.get('/topics')
    },
    getTopicById(id = '5433d5e4e737cbe96dcef312') {
      return axios.get(`/topic/${id}`)
    }
  },
  modules: {
    // 有命名空間的請(qǐng)求,命名空間就是 topic
    topic: {
      getTopics() {
        return axios.get('/topics')
      },
      getTopicById(id = '5433d5e4e737cbe96dcef312') {
        return axios.get(`/topic/${id}`)
      }
    }
  }
}

export default ajaxLoading({
  store,
  service
})

完成以上配置之后,通過(guò)上面 export default 出來(lái)的對(duì)象去發(fā)送請(qǐng)求,就會(huì)自動(dòng)設(shè)置請(qǐng)求的狀態(tài),然后可以在組件內(nèi)通過(guò) this.$store.state.loading this.$loading 去訪問(wèn)請(qǐng)求狀態(tài),如:

<el-button type="primary" :loading="$loading.getTopics" @click="handler1">getTopics</el-button>
<el-button type="primary" :loading="$loading.delay" @click="delay">定時(shí)兩秒</el-button>
<el-button type="primary" :loading="$loading.topic.getTopics" @click="handler3">topic.getTopics</el-button>

import api from 'path/to/api'
export default {
  methods: {
    handler1() {
      api.getTopics()
    },
    handler3() {
      api.topic.getTopics()
    },
    delay() {
      api.delay()
    }
  }
}

Options
store

Vuex.Store 創(chuàng)建的實(shí)例

service

包含所有請(qǐng)求的對(duì)象,可以配置 global 和 modules 屬性

  • global:全局作用域的請(qǐng)求,可以設(shè)置為 對(duì)象 或 數(shù)組對(duì)象
  • modules:帶命名空間的請(qǐng)求,類型為 對(duì)象 ,屬性名即為命名空間

總結(jié)

以上所述是小編給大家介紹的為vue項(xiàng)目自動(dòng)設(shè)置請(qǐng)求狀態(tài)的配置方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!

相關(guān)文章

最新評(píng)論