Vue.js 文字滚动组件封装与应用
什么是文字滚动组件?
文字滚动组件是一种 UI 元素,允许文本在有限的空间内连续滚动,显示不断变化的内容。
如何封装 Vue.js 文字滚动组件?
立即学习“前端免费学习笔记(深入)”;
1. 创建组件文件
创建一个新的 Vue.js 文件,如 TextScroller.vue:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<template>
<div class="text-scroller">
<div class="text" v-html="text"></div>
</div>
</template>
<script>
export default {
props: [text],
data() {
return {
position: 0
}
},
methods: {
scroll() {
this.position -= this.scrollSpeed;
if (this.position < -this.textWidth) {
this.position = 0;
}
},
updateTextWidth() {
this.textWidth = this.$el.querySelector(.text).getBoundingClientRect().width;
}
},
created() {
this.scrollSpeed = 2;
this.updateTextWidth();
setInterval(this.scroll, 50);
}
}
</script>
<style>
.text-scroller {
overflow: hidden;
width: 100%;
}
.text {
position: absolute;
white-space: nowrap;
}
</style>
2. 注册组件
在主 Vue 实例中注册组件:
1
2
3
import TextScroller from ./TextScroller.vue;
Vue.component(text-scroller, TextScroller);
如何应用 Vue.js 文字滚动组件?
在模板中使用组件:
1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<text-scroller :text="text"></text-scroller>
</template>
<script>
export default {
data() {
return {
text: 滚动文字内容
}
}
}
</script>