vue3 watch 函数节流 制作自己的二维码生成器

时间秒杀一切 提交于 2020-08-11 11:50:36

将输入框里面的字符串实时的转成二维码

 

在input内容改变的时候生成二维码, 但是可以看到每次都会触发这个生成操作

 

用lodash的节流函数包一层, 这样就能看到基本是达到了效果, 减少了很多次函数调用

为了看到效果, 下面是200ms的输出

 

 

<template>
  <div>
    <textarea
      v-model="text"
      cols="30"
      rows="10"
      placeholder="请输入文本..."
    ></textarea>
    <img src="" alt="" ref="imgRef" />
  </div>
</template>

<script>
import { ref, onMounted, watch } from "vue";
import QRCode from "qrcode";
import throttle from "lodash-es/throttle";

export default {
  setup() {
    const text = ref("");
    const imgRef = ref(null);
    const handleInput = throttle(() => {
      console.log("watch", text.value);
      QRCode.toDataURL(text.value || "hello world!").then(
        (url) => imgRef.value && (imgRef.value.src = url)
      );
    }, 100);
    watch(text, handleInput, {
      immediate: true,
    });
    return {
      text,
      imgRef,
    };
  },
};
</script>

<style></style>

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!