This article helps you to solve the problems encountered in using axios data request in vue.js

Keywords: axios Vue npm

Words written in the front:
In the development process of using vue environment, using axios to request data interface has become the first choice, and it is also an officially recommended scheme of vuejs. This article mainly introduces the use of axios from the following two examples, in order to let you understand how to use axios under the vue framework:
1, Direct call (understand the principle and related settings)
1. Using npm to install axios dependency

cnpm install axios -S

After installation, you can see a dependency in the dependency file package.jason

2. Import axios directly into components and make corresponding configuration

// Step 1: introduce the Vue and axios plug-ins
import axios from 'axios'
// Step 2: set the server address and port number
axios.defaults.baseURL = 'http://www.yuyunit.com:8083/'
// Step 3: set the default token
axios.defaults.headers.common['Authorization'] = ''
// Step 4: set request header format
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
const url = 'CateringSystem1.0/recruitment/catering/qryMenuClassList.do?method=login'
// Step 5: new a parameter instance and pass the parameter
let params = new URLSearchParams()
params.append('deskId', sessionStorage.getItem('Did'))
// Step 6: get the data returned by the background. then()
axios.post(url, params).then((data) => {
this.asidearray = data.data.responseBody.menuClassList
})

2, Register axios as a global plug-in for vue
1. Installation dependency (same as above)
2. Encapsulate the Axios method in an axios.js file and export it

import axios from 'axios'

axios.defaults.baseURL = 'http://www.yuyunit.com:8083/'
axios.defaults.headers.common['Authorization'] = ''
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

export default axios

3. Introduce axios.js in the main.js file, and use vue.prototype.$axios to register as a global plug-in

import Vue from 'vue'
import App from './App'
import router from './router'
// Introducing axios
import axios from './commonjs/axios'

// Register as a global plug-in
Vue.prototype.$axios = axios
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  axios,
  components: { App },
  template: '<App/>'
})

4. Then we can use this.$axios to request data in other components just like we use other plug-ins

 this.$axios.post(urls.login, params).then((data) => {
        console.log(data)
      }).catch(() => {
        alert('request was aborted')
      })

Finally, common errors in the process of work: TypeError: Cannot read property 'prototype' of undefined
The solution is to use vue.prototype.axios = axios to register as a global plug-in (refer to the settings in step 2), instead of vue.use(axios). Because axios is not a plug-in to vue.

Posted by shareaweb on Fri, 20 Dec 2019 06:36:56 -0800