【发布时间】:2018-07-29 20:45:39
【问题描述】:
父视图我有以下模板代码:
<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 调用。
我的问题是:在浏览器中呈现视图后,如何循环遍历所有员工卡元素并更新将存在于父模板中的 setInterval 函数中的值。
【问题讨论】:
-
Vue 是数据驱动的。使用 Vue 最惯用的方法是在员工对象上设置一个值,员工卡只需对其模型的更改做出反应。无需手动触发任何东西。假设您有一个
status,当该值更改时,更改应自动反映在子组件中。 -
嗨,Bert,知道了,但在我的父视图中,我如何访问使用 v-for 呈现的特定子组件。我的意思是如果我只想更改特定员工的状态会发生什么。
-
更改特定员工的数据。在父级中,您有完整的员工列表。如果您更改该数据,则更改应自动反映在该员工传递给的子项中。你不必触发任何东西。
-
太棒了 :),所以我的 setInterval 函数可以这样开箱即用,对吗?
-
应该,是的。
标签: javascript vue.js vuejs2