1. 程式人生 > >vue.js---加載JSON文件的兩種方式

vue.js---加載JSON文件的兩種方式

發現 bsp 配置文件 方式 error clas api 引入 lan

本周的項目有個需求,需要把打包好的項目,通過直接變更JSON的配置文件,動態的渲染頁面。。

這裏我嘗試了兩種方式:

方法一:

通過import直接引入,直接調用data即可獲取json文件的內容。

import data from ‘static/h5Static.json‘

該方法比較直接,但是打包以後發現變更JSON文件,結果渲染的頁面還是與最初打包JSON文件渲染出來的頁面一樣,並不能達到我想要的結果,因此嘗試了方法二。

方法二:

通過axios請求的方式,可參考上一篇博客axios的封裝

1.在http.js中添加一個請求方法

export const $getJson = function
(method) { return new Promise((resolve, reject) => { axios({ method: ‘get‘, url: method, dataType: "json", crossDomain: true, cache: false }).then(res => { resolve(res) }).catch(error => { reject(error) }) })

2.接口的封裝文件中引入$getJson

請求方式

import{$get,$post,$getJson}from ‘../http‘;

//獲取JSON數據
const getH5StaticJson = data => {
  return $getJson(‘static/h5Static.json‘,data)
}

3.在組建中使用

this.$api.user.getH5StaticJson({}).then(res => {
      consloe.log(res)
 });

vue.js---加載JSON文件的兩種方式