首页 > 解决方案 > vue.js 上的红绿灯不工作,如何解决?

问题描述

我使用 vue.js 创建了一个红绿灯,但它不起作用。它应该根据持续时间显示颜色(红色、黄色和绿色)。有没有我错过的问题?

CSS

#screen {
width: 450px;
height: 740px;
background: #222; 
border-radius: 12px;
margin: auto;
padding: 23px;
}

.light {
    width: 230px;
    height: 270px;
    display: inline-block;
    opacity: 0.2;
    border-radius: 100%;
    transition: opacity 10s;
    margin-bottom: 12px;
}

.active {
    opacity: 1;
}
.red {
    background: red;
}

.yellow {
    background: yellow;
}

.green {
    background: green;
}

我的 HTML 我已经创建了 div。


<div id="screen">
<div id="light red"  :class="{active: now=='red'}"></div>
<div id="light yellow"  :class="{active: now=='yellow'}"></div>
<div id="light green"  :class="{active: now=='green'}"></div>
</div>

这是 vue.js 似乎所有内容都在它的位置,并且控制台没有发送任何错误。但我仍然无法理解,为什么它不起作用?

class State {
  constructor(name, dur, next){
    this.name = name;
    this.dur = dur;
    this.next = next;
  }
}

class Constroller {
  trigger(state, callback){
    callback(state);
    setTimeout(()=>{
      this.trigger(state.next, callback);
    }, state.dur * 10)
  }
}


var app = new Vue({
el: '#screen', 
  data:{
    now: 'red'
  },
  mounted(){
    var constroller = new Constroller();

    var red = new State('red', 2);
    var yellowRed = new State('yellow', 1);
    var yellowGreen = new State('yellow', 1);
    var green = new State('green', 3);

    red.next = yellowRed;
    yellowR.next = green;
    green.next = yellowGreen;
    yellowG.next = red;

    constroller.trigger(red, (state)=>{
      this.now = state.name;
    });

  }
})

我错过了什么吗?我应该重写我的函数吗?

标签: htmlcssvue.js

解决方案


好吧,这里有几件事是错误的:

<div id="light red"  :class="{active: now=='red'}"></div>
<div id="light yellow"  :class="{active: now=='yellow'}"></div>
<div id="light green"  :class="{active: now=='green'}"></div>

应该是类而不是 id。

var red = new State('red', 2);
var yellowRed = new State('yellow', 1);
var yellowGreen = new State('yellow', 1);
var green = new State('green', 3);

red.next = yellowRed;
yellowR.next = green;
green.next = yellowGreen;
yellowG.next = red;

你命名yellowRedyellowGreen但随后使用yellowRYellowG

无论如何,我在这里做了一个快速的小提琴https://jsfiddle.net/Lo50j4rw/你可以看看,我还调整了一些持续时间的东西。
此外,至少在我的国家,红灯后灯变绿:D


推荐阅读