当前位置: 首页>>知识库
阅读次数:463
vue引用json文件的方法小结

var getData = require("./taifeng.json"); // 直接引入json文件

console.log(getData);

   

vue中引用Json文件

我们用import引用文件的时候,被引用的文件都会用export暴漏,比如js,而有一些文件不需要暴漏,如Json、img(图片)、css;

import 引用Json文件


import aaaa from "./a.json"

//aaaa是变量,可以随便命名

   

完成! 没想到吧 就是这么简单 我在网上搜到的都是使用axios来进行转换 那个对于我这个脑袋不太好使的人属实不友好 所以还是这个简单高效 完美!

Vue 中引入 json 的三种方法

json的定义:

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。
JSON 是 JS 对象的字符串表示法,它使用文本表示一个 JS 对象的信息,本质是一个字符串。

1.require-运行时加载

test.json文件


   

{

  "testData": "hello world",

  "testArray": [1,2,3,4,5,6],

  "testObj": {

    "name": "tom",

    "age": 18

  }

}


   

// 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();

},

   


责任编辑:运营部

Copyright © 2019 南京乐芮天信息科技有限公司 苏ICP备19074256号-1
联系我们