vue3+ts 指定五个背景颜色循环展示
时间: 2023-09-17 16:07:59 浏览: 143
可以使用 Vue3 的 Composition API 和 TypeScript 来实现指定五个背景颜色循环展示的功能。
首先,需要在组件中定义一个响应式的 `colorIndex` 变量来记录当前展示的颜色索引:
```typescript
import { defineComponent, reactive } from 'vue'
export default defineComponent({
setup() {
const state = reactive({
colorIndex: 0
})
return {
state
}
}
})
```
然后,在模板中使用 `:style` 绑定来动态设置背景颜色,使用计算属性来计算当前展示的颜色:
```html
<template>
<div :style="{ backgroundColor: currentColor }">
<!-- content -->
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, computed } from 'vue'
export default defineComponent({
setup() {
const state = reactive({
colorIndex: 0
})
const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#00ffff']
const currentColor = computed(() => colors[state.colorIndex])
return {
state,
currentColor
}
}
})
</script>
```
最后,在定时器中更新 `colorIndex` 变量,实现循环展示五个背景颜色的效果:
```html
<template>
<div :style="{ backgroundColor: currentColor }">
<!-- content -->
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, computed, onMounted } from 'vue'
export default defineComponent({
setup() {
const state = reactive({
colorIndex: 0
})
const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#00ffff']
const currentColor = computed(() => colors[state.colorIndex])
onMounted(() => {
setInterval(() => {
state.colorIndex = (state.colorIndex + 1) % colors.length
}, 1000)
})
return {
state,
currentColor
}
}
})
</script>
```
阅读全文