Vue中引入json的三種方式總結(jié)
更新時間:2023年05月17日 17:01:09 作者:青顏的天空
這篇文章主要介紹了Vue中引入json的三種方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
vue引入json的三種方式
json的定義
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。
JSON 是 JS 對象的字符串表示法,它使用文本表示一個 JS 對象的信息,本質(zhì)是一個字符串。
1.require-運(yùn)行時加載
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();
},vue解析json數(shù)據(jù)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script><!--vue.min.js的庫-->
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script><!--jQuery庫-->
</head>
<body>
<div id="main">
<div v-for="item in rows">
<p>姓名:{{item.name}}</p>
<p>昵稱:{{item.nick}}</p>
</div>
</div>
</body>
<script>
$(document).ready(function () {
$.getJSON("data.json", function (result, status) {
var v = new Vue({
el: '#main',
data: {
rows: result
}
})
});
});
</script>
</html>test.json
[
{
"name": "王小婷",
"nick": "祈澈菇?jīng)?
}, {
"name": "安安",
"nick": "壞兔子"
}, {
"name": "編程微刊",
"nick": "簡書"
}
]總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue+element樹組件 實現(xiàn)樹懶加載的過程詳解
這篇文章主要介紹了vue+element樹組件 實現(xiàn)樹懶加載的過程,本文通過圖文實例代碼相結(jié)合給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10
前端項目vue3/React如何使用pako庫解壓縮后端返回gzip數(shù)據(jù)
pako是一個流行的JS庫,用于在瀏覽器中進(jìn)行數(shù)據(jù)壓縮和解壓縮操作,它提供了對常見的壓縮算法的實現(xiàn),使開發(fā)者能夠在客戶端上輕松進(jìn)行數(shù)據(jù)壓縮和解壓縮,這篇文章主要介紹了前端項目vue3/React使用pako庫解壓縮后端返回gzip數(shù)據(jù),需要的朋友可以參考下2024-07-07
VUE實現(xiàn)一個Flappy Bird游戲的示例代碼
這篇文章主要介紹了VUE實現(xiàn)一個Flappy Bird的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
探索Vue.js component內(nèi)容實現(xiàn)
這篇文章主要和大家一起探索Vue.js component內(nèi)容實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11

