大纲
安装vue-axios 全域使用结合 Vuex action 使用
安装
npm i --save axios npm i vue-axios
vue-axios 方法
写于 main.js元件中 使用 this.axios
// 于 main.js 引用 import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios) // 于 元件 生命週期中 使用 axios api call mounted() { this.axios.get('http://localhost:3000/users') .then((res) => { console.table(res.data) }) .catch((error) => { console.error(error) }) this.axios({ method: 'get', baseURL: 'http://localhost:3000', url: '/users', 'Content-Type': 'application/json', }) .then((result) => { console.log(result.data) }) .catch((err) => { console.error(err) }) },
Vuex action & axios 实体
写于 store.jsWhy use axios 实体
// 引入 Vuex store.js import axios from 'axios' // 建立 axios 实体 统一管理 config const userRequest = axios.create({ baseURL: 'http://localhost:3000', headers: { 'Content-Type': 'application/json' }, }) // store.js action 撰写 api call actions: { getUsers() { return userRequest.get('/users') }, }, // 元件生命週期中 使用 dispatch 呼叫该 api created(){ this.$store.dispatch('getUsers') .then((result) => { console.table(result.data) }) .catch((err) => { console.error(err) }) }
参考资料
vue全域性使用axios的方法