我希望你能帮助我。我试图根据API调用动态显示一些按钮。我只是设法在页面呈现之前设法接收数据。
new Vue({
el: '#app',
data : function(){
return{
results : [],
}
},
beforeCreate : function(){
axios.get('somesite')
.then(function (response) {
this.results = response.data;
console.log(this.results);
})
.catch(function (error) {
console.log(error);
});
},
})
和html是:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
{% raw %}
<div class="container">
<div id="app">
<div class="response_list">
<button class="entries" v-for="entry in results"></button>
</div>
</div>
</div>
{% endraw %}
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/index.js') }}"></script>
</body>
</html>
答案 0 :(得分:0)
您似乎没有绑定beforeCreate
承诺函数中axios
方法的上下文。
通过使用forward arrow function
将组件的context
绑定到axios
promise函数,您将能够正确更新组件数据对象:
beforeCreate : function(){
axios.get('/')
.then((response) => {
this.results = response.data
console.log(this.results)
})
.catch((error) => {
console.log(error)
});
},