vue引用json文件的方法小結(jié)
相信大家都有被后端數(shù)據(jù)支配過 廢話不多說 直接上代碼
1.解決怎么從控制臺把數(shù)據(jù) 移到j(luò)son文件中 直接右擊復(fù)制值
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是變量,可以隨便命名
完成! 沒想到吧 就是這么簡單 我在網(wǎng)上搜到的都是使用axios來進(jìn)行轉(zhuǎn)換 那個對于我這個腦袋不太好使的人屬實不友好 所以還是這個簡單高效 完美!
Vue 中引入 json 的三種方法
json的定義:
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。
JSON 是 JS 對象的字符串表示法,它使用文本表示一個 JS 對象的信息,本質(zhì)是一個字符串。
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根據(jù)依賴編譯,無法作為路徑使用,static中的文件才可以作為路徑用 const {testData, testArray, testObj} = res.data; } }, mounted() { this.jsonHttpTest(); },
參考鏈接:https://www.jianshu.com/p/6839ffe69338
到此這篇關(guān)于vue引用json文件的文章就介紹到這了,更多相關(guān)vue引用json文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- npm如何更新VUE package.json文件中依賴的包版本
- vue項目如何讀取本地json文件數(shù)據(jù)實例
- Vue讀取本地靜態(tài)文件json的2種方法以及優(yōu)缺點
- 在vue中讀取本地Json文件的方法
- Vue實現(xiàn)數(shù)據(jù)導(dǎo)入的四種方法(resource、Axios、Fetch、Excel導(dǎo)入)
- vue?組件異步加載方式(按需加載)
- 解決vue動態(tài)路由異步加載import組件,加載不到module的問題
- vue異步加載高德地圖的實現(xiàn)
- Vue中JSON文件神奇應(yīng)用fetch、axios異步加載與模塊導(dǎo)入全指南詳細(xì)教程
相關(guān)文章
Vue2過渡標(biāo)簽transition使用動畫方式
這篇文章主要介紹了Vue2過渡標(biāo)簽transition使用動畫方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07