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

先看一下效果:
vue封装基础input组件(添加防抖功能)_第1张图片

// 调用页面
<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>

你可能感兴趣的:(面试,vue.js,前端,javascript)