Vue踩坑紀錄- axios 數據獲取
項目使用套件
前端: Vue, Vuetify
後端: Flask, Flask-cors
數據庫: MongoDB
前後通訊: axios
flask代碼
@app.route("/dashboard", methods= ['GET'])
def key_index():
key_index = db.sns.find({},{"_id":0}).sort([("datetime", -1)])
return dumps(key_index)
except Exception as e:
return dumps({'error': str(e)})
-GET methods 獲取資料庫的數據, 並以json格式回傳
json 數據
{
datetime: "2021-01-21 22:17:18",
sns: {
example1: 367,
example2: 953.5,
example3: 1682124
}
},
Axios通訊
在 /frontend/main.js中加入:
import axios from 'axios'
Vue.prototype.$axios = axios
Vue.config.productionTip = false;
Vue- 獲取並處理json數據
export default {
name: 'Dashboard',
data() {
return {
//define data
//全部先以null初始
indexes: "",
example1: "",
example2: "",
example3: ""
}
},
//create method
created() {
this.getData();
},
methods: {
getData() {
this.$axios.get('/api/route_name')
.then(res => {
//獲取第一筆json數據
this.indexes = res.data[0];
//獲取第一筆json數據中sns裡的example1
this.example1 = res.data[0].sns.example1,
this.example2 = res.data[0].sns.example2,
this.example3 = res.data[0].sns.example3
})
.catch(err => {
console.log(err);
})
}
因數據庫存取的數據單位不同,須另行計算再display
computed: {
//return M unit in each index
example1_display() {
return (this.example1 / 100).toFixed(3)
},
Vue呈現頁面
原先直接以 {{ }}呈現,雖然還是可以render 但會報錯!
報錯原因: 後端傳來的data還沒load成功,render為空
解決辦法: 以v-if 來判斷data是否load,load成功才呈現於頁面
//報錯
<span>{{ example1_display }}</span>
//解決辦法
<span v-if="indexes">{{ example1_display }}</span>