练手用小功能:

vue 中DOM选择
动态添加 Object 数据绑定
setInterval 循环控制
Math.floor取整 padEnd补零

DOM部分

生成颜色的数量由 v-for 的循环数控制

        <div ref="ttcc">
            <p v-for="index in 8" :key="index" :style="testColor[index-1]" >{{testColor[index-1]}}  {{index}} {{Object.keys(testColor).length}}  随机颜色</p>
            <button @click="testClick"> Stop interval</button>
        </div>

根据标签初始化保存颜色的对象

用set添加能有数据绑定关系;
【注】开始使用数组记录颜色,由于JS 监听不到数组值的变化才改用的对象;
$refs 的DOM操作需要创建完 vue 实例后再执行,否则拿不到 children 的数量

data() {
        return {
            testColorInterval: '',
            testColor: { }
        }
mounted() {
        for (let k=0;k<this.$refs.ttcc.children.length;k++) {
            this.$set(this.testColor, k, '')
        }
        this.tColor();
    }

循环生成颜色 和 停止/启动循环

testClick 是用来停止/启动循环
tColor 是循环生成颜色

methods: {
        testClick() {
            if (this.testColorInterval != '') {
                clearInterval(this.testColorInterval);
                this.testColorInterval = '';
            } else {
                this.tColor();
            }
        },
        tColor() {
            let _this = this;
            this.testColorInterval = setInterval(() => {
                for (let key in _this.testColor) {
                    _this.testColor[key] = `color: #${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
                }
            }, 300);
        }
}

cason6810
110 声望7 粉丝

引用和评论

0 条评论