vue實現(xiàn)公告欄文字上下滾動效果的示例代碼
本文詳細的介紹了vue實現(xiàn)公告欄文字上下滾動效果的示例代碼,分享給大家,具體入如下:
代碼實現(xiàn):
在項目結構的components中新建text-scroll.vue文件
<template>
<div class="text-container">
<transition class="" name="slide" mode="out-in">
<p class="text" :key="text.id">{{text.val}}</p>
</transition>
</div>
</template>
<script>
export default {
name: 'TextScroll',
props: {
dataList: {
type: Array,
default() {
return [];
},
},
},
data() {
return {
count: 0, // 當前索引
intervalId: null, // 定時器ID
playTime: 2000, // 定時器執(zhí)行間隔
};
},
computed: {
text() {
return {
id: this.count,
val: this.dataList[this.count],
};
},
},
created() {
this.intervalId = setInterval(() => { // 定義定時器
this.getText();
}, this.playTime);
},
methods: {
getText() {
const len = this.dataList.length; // 獲取數(shù)組長度
if (len === 0) {
return; // 當數(shù)組為空時,直接返回
}
if (this.count === len - 1) { // 當前為最后一個時
this.count = 0; // 從第一個開始
} else {
this.count++; // 自增
}
},
},
destroyed() {
clearInterval(this.intervalId); // 清除定時器
},
};
</script>
<style scoped>
.text-container{
font-size: 14px;
color: #F56B6B;
margin-right: 20px;
height: 60px;
}
.text {
text-align: right;
margin: auto 0;
}
.slide-enter-active, .slide-leave-active {
transition: all 1s;
}
.slide-enter{
transform: translateY(40px);
}
.slide-leave-to {
transform: translateY(-40px);
}
</style>
在header-bar組件使用
<text-scroll :dataList="noticeList"></text-scroll>
分析
transition標簽

這里是動態(tài)組件
官方文檔:https://cn.vuejs.org/v2/guide/transitions.html
為什么用setInterval,而不是setTimeout
setInterval是循環(huán)執(zhí)行,setTimeout是延遲執(zhí)行。我們這里要的是setTimeout循環(huán)執(zhí)行。通過嵌套setTimeout可以實現(xiàn)循環(huán),但是每次都會注冊一個計時器,然后時間上也是需要等當前setTimeout執(zhí)行完再延遲比如說兩秒執(zhí)行,實際上就不只2s。
什么情況下setTimeout嵌套可以解決 setInterval 解決不了的問題 當計時器是高耗時的計算或者dom操作時,時間大于延遲時間
到此這篇關于vue實現(xiàn)公告欄文字上下滾動效果的示例代碼的文章就介紹到這了,更多相關vue 公告欄文字上下滾動 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue(element ui)中操作row參數(shù)的使用方式
這篇文章主要介紹了Vue(element ui)中操作row參數(shù)的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
Element樹形控件整合帶圖標的下拉菜單(tree+dropdown+input)
Element UI 官網(wǎng)提供的樹形控件包含基礎的、可選擇的、自定義節(jié)點內(nèi)容的、帶節(jié)點過濾的以及可拖拽節(jié)點的樹形結構,本文實現(xiàn)了樹形控件整合帶圖標的下拉菜單,感興趣的可以了解一下2021-07-07
Element-ui table中過濾條件變更表格內(nèi)容的方法
下面小編就為大家分享一篇Element-ui table中過濾條件變更表格內(nèi)容的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03

