我是vue和Laravel框架的新手。
我想从 api 获取数据并动态显示这些数据。
我创建了一个名为“ Progress”的表,并植入了一些数据。我已经使用API资源来获取数据。
我已经创建了一个vue模板以从api中获取数据。
这是我的模板
<template>
<div class="container">
<h1> Goals </h1>
<p id="demo"></p>
<div class= "progress progress-bar-segmented" v-for = "progressdata in progress" v-bind:id="progressdata.id">
<div> {{ progressdata.name }} </div>
<div id="div1" class="progress-bar" style="width:20%">{{ progressdata.goal }}</div>
<div id="div2" class="progress-bar value" style="width:20%">{{ progressdata.value }}</div>
</div>
</div>
</template>
问题是如何从脚本中的进度数组访问{{ progressdata.goal }}
和{{ progressdata.value }}
之类的单个值?
如果我在方法内使用var a = this.progressdata.goal
。我可以收到undefined value
我知道它们只能在该范围内访问。如何在脚本中单独访问它们?
这是我的剧本
<script>
export default {
data: function() {
return {
progress: [],
}
},
mounted() {
this.loadContents();
this.start();
setInterval(this.loadContents, 1000);
},
methods: {
loadContents: function() {
//load Api
axios.get('/api/progress')
.then((response) => {
this.progress = response.data.data;
})
.catch(function (error) {
console.log(error);
});
},
start: function() {
var allProgressElements = document.getElementsByClassName('progress');
Array.prototype.forEach.call(allProgressElements, function(el) {
var targetDOM = $(el).getElementsByClassName('value');
targetDOM.innerHTML = json.data[targetDOM.id].value;
});
}
}
}
</script>
Anyone could help please?
thank you.
答案 0 :(得分:1)
这里发生了几件事:
start
函数中的那些内容。Promise
(请参见下面的代码)reactivity
,properties
和范围界定的所有内容。<script>
export default {
data: function() {
return {
progress: [], // The progress array is defined
}
},
mounted() {
// Component mounted, start loading of contents
this.loadContents();
// Note i removed code here! Because that codes was
// executed right after the loadContents call, but
// before the axios result came in!
},
methods: {
loadContents: function() {
//load Api
// The get function returns a promis
axios.get('/api/progress')
.then((response) => {
// Promise resolved, now set the data:
this.progress = response.data.data;
// And now we can perform the start function
this.start()
// Maybe add the setInterval code here, although you need
// to check if you really want to hit your server every second....
// Better to use a websocket and let the server notify you about the progress
})
.catch(function (error) {
console.log(error);
});
},
start: function() {
// And in this function we now have access to the progress array:
for (const item of this.progress) {
console.log(item.goal)
}
}
}
</script>