vue封装基础input组件(添加防抖功能)

2024-01-09 10:17:40

先看一下效果:
在这里插入图片描述

// 调用页面
<template>
  <div>
    <!-- v-model:伪双向绑定   -->
    <my-input v-model="inputVal" label="姓名" type="textarea" />
  </div>
</template>

<script>
import MyInput from './MyInput.vue'
export default {
  name: 'index',
  data () {
    return {
      inputVal: '111'
    }
  },
  components: {
    MyInput
  },
  watch: {
    inputVal (newVal, oldVal) {
      // console.log('新旧值', { newVal, oldVal })
      this.getDataByInputVal()
    }
  },
  created () {
    this.getDataByInputVal = this.debounce(this.getDataByInputVal, 1000)
  },
  methods: {
    debounce (fn, wait = 500) {
      let timer = null
      return function () {
        timer && clearTimeout(timer)
        timer = setTimeout(() => {
          console.log('防抖执行了')
          fn()
        }, wait)
      }
    },
    getDataByInputVal () {
      setTimeout(() => {
        console.log(this.inputVal)
      }, 1000)
    }
  }
}
</script>

<style scoped>

</style>

// my-input组件
<template>
  <div class="my-input">
    <label>{{ label }}</label>
    <input
      v-bind="$attrs"
      @input="$emit('input', $event.target.value)"
    />
  </div>
</template>

<script>
export default {
  name: 'MyInput',
  props: {
    label: {
      type: String,
      required: false
    }
  }
}
</script>

<style scoped>

</style>

文章来源:https://blog.csdn.net/qq_42832446/article/details/135381191
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。