The Vue framework is now very popular for single-page applications.
How can a project created based on VUE-CLI be better able to handle network requests?
The first choice should be Axios.
This time, let's introduce to the new Vue how Axios is used in Vue.
Install the words to the official website to see
First, the method is not recommended
// Import Axios import Axios from ' Axios 'default {' HelloWorld ' in the component to use the network request, data () { return { params:{} } }, methods: {// Call the network request here request () { axios.get (' url${. params} '). Then (result=>{ Console.log (Result)} ) }}}
This method compares Muggle which file to use on the import Axios from ' Axios ', but too cumbersome, also is not conducive to maintenance.
Second, less network requests
//Open main.js Global import AxiosImport Vue from' Vue 'Import App from'./app 'Import Router from'./router 'Import Axios from' Axios '//presence in prototypeVue.prototype. $http =Axios//There are two ways to call when you need to use other components of Axios//Vue $http. Get (' Url${params} ')//This . $http. Get (' Url${params} ')//However, there is a problem with this use, in a separate JS file does not call $http, because there is no Vue instance. In most cases, this is the way to meet most of the requirements.Vue.config.productionTip=false/*eslint-disable no-new*/NewVue ({el:' #app ', router, Template:' <App/> ', components: {APP}})
Third, the recommended method
Using the method two has been able to meet most of the needs, writing time is also relatively cool, but later if the interface changes, but also to find a change, will appear very messy
Recommend a way of doing what you usually do
// Create a new JS named API import Axios from ' Axios ' // import Axios in API let base = '/v1 ' // Write the entire project's network request in this file with export export const getproduct = params = {return axios.get (' $ {base}/product/info/${params} ')}// This makes it easy to manage network requests for the entire project
// If we use this request, say, GetProduct . Import { getproduct ' ... /api/api 'default { ' HelloWorld ', data () { return { params:{} } , methods: { getproductlist () { getproduct (this . Params). Then (result=>{ console.log (result); }) }}} // Note that we export using export, so the import must take {}
Finish!
Several methods of integrating Axios in VUE-CLI