vue 中 json 数据的多种导入方式

1.require-运行时加载

复制代码
// require引用:
mounted() {
    // require引用时,放src和放statci都可以,建议放static
    const testJson = require('../../static/json/test.json');
    const {testData, testArray, testObj} = testJson;
    console.log('testData',testData);
    // ‘hello world’
    console.log('testArray',testArray);
    // [1,2,3,4,5,6]
    console.log('testObj',testObj);
}
复制代码

2.import-编译时输出接口

复制代码
// import 引用
// import引用时,放src和放statci都可以,建议放static
import testImportJson from '../../static/json/test.json'
// import testImportJson from './json/test.json'
export default {
  data(){
    return{
      testImportJson  
    }
  },
  mounted() {
    const {testData, testArray, testObj} = this.testImportJson;
  }
}
复制代码

3.通过http请求获取

复制代码
// http引用
methods:{
  async jsonHttpTest(){
    const res = await this.$http.get('http://localhost:8080/static/json/test.json');
    // 放在src中的文件都会被webpack根据依赖编译,无法作为路径使用,static中的文件才可以作为路径用
    const {testData, testArray, testObj} = res.data;
  }
},
mounted() {
  this.jsonHttpTest();
},
复制代码

转载自:笔名:来碗鸡蛋面
简书主页:https://www.jianshu.com/u/4876275b5a73
邮箱:job_tom@foxmail.com
CSDN ID:tom_wong666

 

posted @   阿玛度の博客  阅读(2536)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示