Javascript VueJS-如何从父v-for调用子组件上的事件
父视图我有以下模板代码:Javascript VueJS-如何从父v-for调用子组件上的事件,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,父视图我有以下模板代码: <template> <employee-card v-for="employee in employees" :key="employee.id" :employee="employee" > </employee-card> </template> <scr
<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>
从“@/components/employee card”导入员工卡;
导出默认值{
组件:{EmployeeCard},
计算:mapGetters({
雇员:“雇员”
}),
方法:{
init(){
this.fetchEmployees();
},
雇员人数(){
//这里有商店的员工
},
validateServerEmployeeStatus(){
//这里调用ajax以获取所有员工的状态
//循环每个员工卡并更新状态
},
},
安装的(){
this.init();
//在这里,我想我应该添加一个setInterval函数来运行
//每60秒,调用validateServerEmployeeStatus()函数
}
};
子组件员工卡模板为:
<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>
{{employee.name}
状态{employee.Status}(每60秒更新一次)
导出默认值{
姓名:“员工卡”,
道具:{
雇员:{type:Object}
},
数据(){
返回{};
},
方法:{}
};
我需要的是每60秒调用一个API
,这将返回我的子组件中所有员工的状态。因此,我必须循环查找所有员工,并更新每个员工卡中的状态标签。我认为这是最好的方法,因为如果我在employeecard
中执行此操作,我会保存API调用
我的问题是:在浏览器中呈现视图后,如何循环所有员工卡元素并更新父模板中的setInterval函数中的值
下面是我在上面的评论中解释的一个例子
Vue是数据驱动的。如果更改数据,DOM将自动更新
下面的状态每秒钟更新一次每个员工的。请注意,仅在EmployeeList
组件中进行更改,而不是在EmployeeCard
中进行更改,但是DOM会自动更新以反映新状态
console.clear()
Vue.组件(“员工卡”{
道具:[“员工”],
模板:`
{{employee.name}
状态{{employee.Status}
`
})
Vue.组件(“员工列表”{
模板:`
`,
数据(){
返回{
员工:[]
}
},
创建(){
axios.get(“https://jsonplaceholder.typicode.com/users")
.然后(response=>this.employees=response.data)
//模拟员工验证
设置间隔(()=>{
让状态=[“好”、“坏”、“meh”]
for(让本公司员工参与){
//设置随机状态
此.$set(员工,“状态”,状态[Math.floor(Math.random()*status.length)])
}
}, 1000)
}
})
新Vue({
el:“应用程序”
})
Vue是数据驱动的。使用Vue执行此操作的最惯用方法是在employee对象上设置一个值,员工卡只对其模型中的更改做出反应。不需要手动触发任何东西。假设您有一个状态
,当该值更改时,更改应自动反映在子组件中。您好,伯特,明白了,但在我的父视图中,如何访问使用v-for呈现的特定子组件。我的意思是,如果我只想更改特定员工的状态,那么会发生什么。更改特定员工的数据。在父级中,您有完整的员工列表。如果您更改该数据,则更改应自动反映在传递给该员工的子级中。你不必触发任何东西。太好了:),所以我的setInterval函数就可以用这种方式开箱即用了,对吗?它应该,是的。真是太棒了,伯特,非常感谢。真正地