vue cli3.0访问本地JSON文件

vue cli3.0访问本地JSON文件


最近练习axios发起数据请求,模拟后台访问数据,发现请求地址一直报错404,查阅了相关资料才知道vue-cli3.0中静态资源要放在static文件夹下。我是通过引入jQuery发起ajax请求,然后地址是static文件夹下的JSON文件,最后数据返回成功。
记录下代码:

created(){
    this.getCarsoul();
  },
  methods:{
    getCarsoul(){   
      $.ajax({
        url: '../static/api/Carsoul.json',
        type: 'get',
        dataType: 'json'
      }).then(
      	function(res){
       	 console.log(res);
     	 },function(error){
        console.log(error.message);
      })
    }

同样,用axios发起get请求也得到结果:

 created(){
    this.getCarsoul();
  },
  methods:{
    getCarsoul(){
     this.$axios.get("../static/api/Carsoul.json").then(result => {
        console.log(result);
      });

vue-cli 目录中,只有static 目录放置的静态文件可以被外部访问。如果想在JSON(static/mock/index.json) 中引入图片地址,必须把图片放在static 目录下。然后JSON 中的图片地址,是你的vue 组件引入图片的地址。我是在src/component/home/home.vue中引入 static/img/1.jpg 图片,图片地址为:"…/…/…/static/img/1.jpg"。 在JSON 中的地址也要这样写。如果配置JSON 时不确定图片地址,可以在你对应的VUE组件中 直接 引入一张图片测试下地址,然后再放在JSON 中。

你可能感兴趣的:(前端,vue,Ajax)