VueCLI3 axios 全域配置

大纲

安装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的方法

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章