vue-cli3 添加 axios 插件

最近在使用vue-cli3 开发用户管理系统后台的时候,使用到axios 插件 读取后台数据json格式文件。
首先: 添加axios, 在vue-cli3 中可以使用命令 vue add axios
1、在项目所在路径打开命令行窗口
D:\vue-sys>vue add axios
在这里插入图片描述
2、在main.js 文件中,已经添加好了import ‘./plugins/axios’ ,可以暂时不做修改,如下

import Vue from 'vue'
import './plugins/axios' 
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

3、在项目文件根目录 新建 vue.config.js 文件,设置代理,

	module.exports = {
	  devServer:{
	    proxy:{
	      '/api':{
	        target:'http://localhost:80',
	        ws:true,
	        changeOrigin:true
	      }
	    }
	  }
	}

其他的代理设置可以查看官网教程:下面贴上地址;
https://cli.vuejs.org/zh/config/#devserver-proxy

4、在组件中使用

<template>
 //此处省略。。。
</template>
<script>
  export default{
    name:'customers',
    data () {
      return {
        customers:[]
      }
    },
    created(){
      this.fetchCustomers()
    },
    methods:{
      fetchCustomers(){
        let that = this
        this.axios.get("/api/db.json")
        .then(function(res){
          console.log(res.data.companies)
          that.customers=res.data.users
        })
      }
    }
  }
</script>

5、结果展示:
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐