家长视图我有以下模板代码:
<template>
<employee-card
v-for="employee in employees"
:key="employee.id"
:employee="employee"
>
</employee-card>
</template>
<script>
import EmployeeCard from '@/components/employee-card';
export default {
components: {EmployeeCard},
computed: mapGetters({
employees: 'employees'
}),
methods: {
init() {
this.fetchEmployees();
},
fetchEmployees() {
// here get employees from store
},
validateServerEmployeeStatus() {
// here call ajax to get all employees status
// loop for each employee card and update the status
},
},
mounted() {
this.init();
// here I guess I should add a setInterval function that runs
// every 60 seconds and call validateServerEmployeeStatus() function
}
};
</script>
儿童组件员工卡模板为:
<template>
<div>
{{ employee.name }}
<br><br>
Status {{ employee.status }} (updated every 60 seconds)
</div>
</template>
<script>
export default {
name: 'EmployeeCard',
props: {
employee: {type: Object}
},
data() {
return {};
},
methods: {}
};
</script>
我需要的是每隔60秒调用一次API
,这将返回我孩子组件中所有员工的status
。那么我必须为所有员工循环并更新每张员工卡中的状态标签。我认为这是最好的方法,因为如果我在employeecard
内进行API调用,我会保存API。
我的问题是:一旦在浏览器中呈现视图,我如何遍历所有员工卡元素并更新将存在于父模板中的setInterval函数中的值。
答案 0 :(得分:1)
以下是我在上述评论中解释的一个例子。
Vue是数据驱动的。如果您更改数据,DOM将自动更新。
每位员工status
以下每秒更新一次。请注意,更改仅在EmployeeList
组件中进行,而不在EmployeeCard
中进行,但DOM会自动更新以反映新状态。
console.clear()
Vue.component("EmployeeCard",{
props: ["employee"],
template: `
<div>
<strong>{{ employee.name }}</strong>
<br><br>
Status {{ employee.status }}
<hr>
</div>
`
})
Vue.component("EmployeeList",{
template: `
<div>
<employee-card v-for="employee in employees" :employee="employee" :key="employee.id"/>
</div>
`,
data(){
return {
employees: []
}
},
created(){
axios.get("https://jsonplaceholder.typicode.com/users")
.then(response => this.employees = response.data)
// simulated employee validation
setInterval(() => {
let status = ["good", "bad", "meh"]
for (let employee of this.employees){
// set a random status
this.$set(employee, "status", status[Math.floor(Math.random()*status.length)])
}
}, 1000)
}
})
new Vue({
el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
<employee-list></employee-list>
</div>