vue中讀取本地Json檔案的方式
阿新 • • 發佈:2022-05-09
vue中讀取本地Json檔案的方式
json案例:
{
"name": "DevilBen",
"url": "https://www.cnblogs.com/devilben/",
"page": 0,
"isNonProfit": true,
"address": {
"street": "浦江鎮",
"city": "上海市閔行區",
"country": "中國"
},
"links": [
{
"name": "部落格園",
"url": "https://home.cnblogs.com/"
},
{
"name": "DevilBen",
"url": "https://www.cnblogs.com/devilben/"
},
{
"name": "百度一下,你就知道",
"url": "https://www.baidu.com/"
}
]
}
json檔案放在static靜態資源包下
方式一:
1,安裝 Axios
npm install axios -s
2,main.js引用 Axios
//引入axios
import axios from "axios"
//使用axios
Vue.prototype.axios = axios
3,鉤子函式獲取檔案
mounted() {
this.axios.get('static/data.json').then(response => this.info = response.data)
}
方式二:
1,安裝vue-resource
npm install vue-resource
2,在main.js檔案中新增:
//引入vue-resource
import VueResource from 'vue-resource'
//使用VueResource
Vue.use(VueResource)
3,通過鉤子函式使用,它的$http.get來讀取json檔案
mounted() {
this.$http.get('static/data.json').then(response => this.info = response.data)
}
完整程式碼:
<template>
<div id="vue">
<div>名稱: