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

},

参考链接:https://www.jianshu.com/p/6839ffe69338