哄女友的模拟输入

151 阅读1分钟

🤔还有两个月就是女友生日,在写生日网站的时候忽然觉得文字直接写出来少了点什么。似乎是少了种期待感。

于是想到了RPG游戏中的经典对话框模式,文字引导着眼睛,一点点阅读完,就像是有人在你耳边诉说着旁边一样。

✨就顺便写了个拟态输入小组件,虽然大概率以后用不到,但还是记录下吧。

效果图

一键复制.gif

代码

组件

<template>
  <div>
    <div v-for="(value, key, index) in typedTextObj" :key="index">
      {{ value.text }}
      <span
        v-if="value.text.length && value.text.length < value.count"
        class="blinkCursor"
        >❤</span
      >
    </div>
  </div>
</template>

<script>
export default {
  name: "analogInput",
  props: {
    typedList: [],
    // 是否无限循环
    loop: {
      type: Boolean,
      default: false
    },
    // 模拟输入速度
    speed: {
      type: Number,
      default: 200
    },
    // 计时器延迟时间
    delayed: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      typedTextObj: {}
    };
  },
  mounted() {
    this.reactive();
    const that = this;
    setTimeout(function() {
      that.start();
    }, this.delayed);
  },
  methods: {
    // 生成响应式数据
    reactive() {
      for (let i = 0; i < this.typedList.length; i++) {
        this.$set(this.typedTextObj, "text" + i, {
          text: "",
          count: this.typedList[i].length
        });
      }
    },
    // 模拟输入事件
    start() {
      let j = 0;
      let k = 0;
      if (this.typedList.length <= 0) {
        return;
      }
      let arr = this.typedList[k].split("");
      let timer = setInterval(() => {
        // 当前行模拟输入
        if (j < arr.length) {
          this.typedTextObj["text" + k].text += arr[j++];
          console.log(this.typedTextObj["text" + k].text);
        } else {
          // 更新换行内容
          if (k < this.typedList.length - 1) {
            k++;
            j = 0;
            arr = this.typedList[k].split("");
            console.log(arr);
          } else {
            clearInterval(timer);
            // 是否无限循环
            if (this.loop) {
              this.start();
            }
          }
        }
      }, this.speed);
    }
  }
};
</script>
<style scoped>
.blinkCursor {
  animation: Blink 1s ease-in 0s infinite;
  color: red;
}
</style>

使用

<template>
  <div>
    <analog-Input
      :typedList="[
        '云想衣裳花想容,春风拂槛露华浓。',
        '若非群玉山头见,会向瑶台月下逢。'
      ]"
      :delayed="10000"
    ></analog-Input>
  </div>
</template>

<script>
import AnalogInput from "../components/analogInput";
export default {
 components: {
    AnalogInput
  }
 };
</script>

<style></style>