[問題探討]vue中json的使用

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

點擊此超鏈接跳轉到Tom哥的博文分類和索引頁面
Tom哥的博客博文分類和索引頁面地址:https://blog.csdn.net/tom_wong666/article/details/84137820

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章