我正在尝试在我的nuxt应用程序的div标签内呈现一个值。
我收到错误消息“无法读取未定义的属性'free_funds'。我是Axios和Nuxt的新手。
原因可能是引导程序需要JQuery来更新标签中的数据吗?我不打算从我在网上看到的示例中使用Jquery。如果您使用Axios来获取数据,则不需要Jquery。
原始json中的api数据如下。
{"count":1,"next":null,"previous":null,"results":
[{"balance":10.0,"exposure":7.0,"free_funds":5.0}]}
如何在div标签内传递免费资金的价值?我希望div标签显示5.0的值
<template>
<div>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<ul class="navbar-nav active">
<li class="nav-item">
<a class="nav-link" href="/monitor">Monitor</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/configuration">Configuration</a>
</li>
<li class="fre-item">
<a class="nav-link">Free Funds</a>
<div class="fre-data" v-if="bal" >{{balance.free_funds}}</div>
<div v-else>not found</div>
</li>
<li class="nav-item">
<a class="nav-link" href="/logout">Logout</a>
</li>
</ul>
</nav>
</body>
</html>
<nuxt/>
</div>
</template>
<script>
export default {
async asyncData () {
try {
const response = await $axios.get('/api/balance/')
return {
bal: response.data.results,
error: true
}
} catch (e) {
console.log('error', e)
data()
return {
balance:{
balance: "",
free_funds: "",
exposure:"",
error: true
}
}
}
}
}
</script>
答案 0 :(得分:0)
仅在获得响应后使用conditional rendering - v-if
使div呈现:
<div class="fre-data" v-if="bal" >{{bal.free_funds}}</div>
,并且在任何情况下(当然也可以在catch块中)将其添加为data属性
答案 1 :(得分:0)
您可以在mounted()
生命周期调用方法中调用API。另外,请参见结果是API响应中的一个数组。试试这个:
<template>
<div>
...
<li v-for="res in results" :key="res.free_funds" class="fre-item">
<a class="nav-link">Free Funds</a>
<div class="fre-data">{{res.free_funds}}</div>
</li>
...
</div>
</template>
<script>
export default {
data() {
return {
results: []
};
},
methods: {
async getBalance() {
try {
const response = await $axios.get('/api/balance/');
this.results = response.data.results;
this.error = false;
} catch(e) {
console.log('error', e);
}
}
},
created() {
this.getBalance();
}
}
</script>