【问题标题】:getElementById on page with multiple instances of same component页面上的 getElementById 具有相同组件的多个实例
【发布时间】:2018-12-11 18:29:23
【问题描述】:

我正在编写一个小型 vue 应用程序。在一个页面上,我包含同一个组件的多个实例,就像这样

<my-component v-for="t in todos"></my-component>

在该组件中,我会显示待办事项的名称和描述以及到期日期等数据。我用这个功能检查是否过期

let d = new Date();
let overdue = false;
this.deadline = new Date(this.deadline);
if (this.deadline < d) { overdue = true; }
if (overdue && !this.completed) {
    document.getElementById('taskCard').style.backgroundColor = 'red';

这可以正确检测任务何时过期,但它总是使第一个待办事项变为红色,而不是过期的待办事项。如何正确定位组件?我的想法是,当我执行 document.getElementById 时,它会找到第一个#taskCard,因为它正在查看页面。有没有办法做类似 this.getElementById 或 my-component.getElementById 的事情?

感谢您的帮助!

【问题讨论】:

  • 可以分享my-component的代码吗?
  • ID 在整个 HTML 页面中应该是唯一的。 getElementById 永远不能指向多个元素。

标签: javascript vue.js


【解决方案1】:

这真的不是“Vue”的做事方式。

相反,您想要做的是让数据驱动您的显示,因此与其尝试查找所有过期的事物并为其设置样式,不如让事物在过期时自行设置样式。

例如

<my-component :style='compstyle' v-for="t in todos"></my-component>

然后在你的组件上有一个属性来绑定那个样式

computed: {
    compstyle : function(){
        return (new Date(this.deadline) < new Date()) ? {'backgroundColor' : 'red'} : {}
    }
}

【讨论】:

  • 感谢您的回答!这非常有帮助,而且是一种非常干净的方法。我是 vue 新手,所以很高兴看到你的思考过程。谢谢!
猜你喜欢
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 1970-01-01
  • 2017-08-01
  • 2019-07-09
  • 1970-01-01
  • 2010-12-03
相关资源
最近更新 更多