我希望遍历一系列span标签,并每3秒将is-active
添加到下一行。我有工作,但在第一个工作之后,其余所有工作都加入了。我该如何从活动类中拉出该类并将其添加到下一个数组项?
我已经阅读了几次官方文档,似乎没有提到迭代单个项目,只是列出所有项目或将项目推入列表。
我不确定'index'是否会在这里播放,以及如何获取span元素的索引以添加/减去is-active
不确定。我在做什么错了?
var firstComponent = Vue.component('spans-show', {
template: `
<h1>
<span class="unset">Make</span>
<br>
<span class="unset">Something</span>
<br>
<span v-for="(span, index) of spans" :class="{ 'is-active': span.isActive, 'red': span.isRed, 'first': span.isFirst }" :key="index">{{ index }}: {{ span.name }}</span>
</h1>
`,
data() {
return {
spans: [
{
name: 'Magical.',
isActive: true,
isRed: true,
isFirst: true
},
{
name: 'Inspiring.',
isActive: false,
isRed: true,
isFirst: true
},
{
name: 'Awesome.',
isActive: false,
isRed: true,
isFirst: true
}
]
};
},
methods: {
showMe: function() {
setInterval(() => {
// forEach
this.spans.forEach(el => {
if (el.isActive) {
el.isActive = false;
} else {
el.isActive = true;
}
});
}, 3000);
}
},
created() {
window.addEventListener('load', this.showMe);
},
destroyed() {
window.removeEventListener('load', this.showMe);
}
});
var secondComponent = Vue.component('span-show', {
template: `
<span v-show="isActive"><slot></slot></span>
`,
props: {
name: {
required: true
}
},
data() {
return {
isActive: false
};
}
});
new Vue({
el: "#app",
components: {
"first-component": firstComponent,
"second-component": secondComponent
}
});
.container {
position: relative;
overflow: hidden;
width: 100%;
}
.wrapper {
position: relative;
margin: 0 auto;
width: 100%;
padding: 0 40px;
}
h1 {
font-size: 48px;
line-height: 105%;
color: #4c2c72;
letter-spacing: 0.06em;
text-transform: uppercase;
font-family: archia-semibold, serif;
font-weight: 400;
margin: 0;
height: 230px;
}
span {
position: absolute;
clip: rect(0, 0, 300px, 0);
}
span.unset {
clip: unset;
}
span.red {
color: #e43f6f;
}
span.is-active {
clip: rect(0, 900px, 300px, -300px);
}
<div id="app">
<div class="container">
<div class="wrapper">
<spans-show>
<span-show></span-show>
</spans-show>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
答案 0 :(得分:1)
要获得理想的结果,我建议稍微改变一下方法。
我们可以创建一个变量(例如isActive
,而不是更改单个项目的activeSpan
的值,该变量将负责当前有效跨度并随时间增加。
setInterval(() => {
// Increment next active span, or reset if it is the one
if (this.activeSpan === this.spans.length - 1) {
this.activeSpan = 0
} else {
this.activeSpan++
}
}, 3000);
在组件的模板中,我们使类is-active
有条件,并依赖于activeSpan
变量:
:class="{ 'is-active': index === activeSpan, 'red': span.isRed, 'first': span.isFirst }"
如果您仍然需要更新spans
数组中的值,可以通过更简单的方式来完成,例如通过map
。在下面的解决方案中还包括可选的情况。
工作示例: JSFiddle
旁注:无需为load
事件添加窗口侦听器,因为在DOM准备就绪后将加载应用程序本身。相反,可以在created
挂钩内调用方法。它包含在上面的解决方案中。