vue项目动态加载JSON并显示

68 篇文章 0 订阅
31 篇文章 0 订阅

1. 封装JSON请求方法

1> 安装 axios

npm install axios

2> 引入并封装axios请求

路径 src/utils/requestJSON.js

import axios from 'axios';

// create an axios instance
const service = axios.create({
  method: 'get',
  crossDomain: true,
  dataType: 'json',
  baseURL: '',
  // withCredentials: true, 
  // send cookies when cross-domain requests
  timeout: 5000 // axios.createrequest timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    return config;
  },
  error => {
    // do something with request error
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or code
   * Please return  response => response
  */

  /**
   * Determine the request code by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    // console.log(response);
    if (!res) {
      const errorMsg = 
      	response.config.url ? `加载"${response.config.url}"失败` 
      		: '请指定所需加载的JSON地址';
      alert(errorMsg);
      return Promise.reject(new Error(errorMsg));
    }
    return res;
  },
  error => {
    alert(error.message);
    return Promise.reject(error);
  }
);

export default service;

3> 封装请求JSON接口

路径 src/api/getJSON.js

import requestJSON from '@/utils/requestJSON';

/**
 * @description 加载JSON文件
 * @param { string } url
 */
export function getJSON(url) {
  return requestJSON({
    url
  });
}

2. 加载并显示JSON

<!-- 偷懒用textarea直接输出json文本, readonly是不让用户编辑 -->
<template>
	<textarea readonly :value="value" />
</template>

<script>
import getJSON from '@/api/getJSON';
export default {
	data() {
		return {
			value: ''
		}
	},
	created() {
	    const jsonURL = '/path/data.json'; //	某个json文件
		getJSON(jsonURL).then(json => {
			this.value = JSON.stringify(json, null, 2);
		})	
	}
}
</script>

JSON.stringify() 方法将一个 JavaScript 对象或值转换为 JSON 字符串


效果如下

在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值