VUE中json的使用

原创声明

本文系作者辛苦码字所得,欢迎分享和转载,但请在明显位置注明作者的如下信息:
笔名:来碗鸡蛋面
简书主页:https://www.jianshu.com/u/4876275b5a73
邮箱:job_tom@foxmail.com
CSDN ID:tom_wong666

json的定义:

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

vue中json的用法一: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 testJson = require('./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);
    //    {
    //    "name": "tom",
    //    "age": 18
    //  }
}

vue中json的用法二:import-编译时输出接口

test.json文件
{
  "testData": "hello world",
  "testArray": [1,2,3,4,5,6],
  "testObj": {
    "name": "tom",
    "age": 18
  }
}
// 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;
    console.log('testImportData',testData);
    // ‘hello world’
    console.log('testImportArray',testArray);
    // [1,2,3,4,5,6]
    console.log('testImportObj',testObj);
    //    {
    //    "name": "tom",
    //    "age": 18
    //  }
  }
}

vue中json的用法三:通过http请求获取

test.json文件
{
  "testData": "hello world",
  "testArray": [1,2,3,4,5,6],
  "testObj": {
    "name": "tom",
    "age": 18
  }
}
// http引用
methods:{
  async jsonHttpTest(){
    const res = await this.$http.get('http://localhost:8080/static/json/test.json');
    // 放在src中的文件都会被webpack根据依赖编译,无法作为路径使用,static中的文件才可以作为路径用
    // const res = await this.$http.get('http://localhost:8080/src/page/json/test.json');
    const {testData, testArray, testObj} = res.data;
    console.log('testHttpData',testData);
    // ‘hello world’
    console.log('testHttpArray',testArray);
    // [1,2,3,4,5,6]
    console.log('testHttpObj',testObj);
    //    {
    //    "name": "tom",
    //    "age": 18
    //  }        
  }
},
mounted() {
  this.jsonHttpTest();
},
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容