vue3.0学习笔记 (customRef自定义防抖)

1.开始customRef

<template>

<input type="text" v-model="imputValue">

<h3>{{imputValue}}</h3>

</template>

<script>

import {customRef} from 'vue'

export default {

  setup(){
    //custom传进去
    let imputValue=custom('请输入')

    //custom方法接收
    function custom(value){
        return customRef(()=>{
          return {
            set(){

            },
            get(){
              return  value
            }
          }
        })
    }

    //最后返回出去
    return {
      imputValue
    }
  }
}
</script>


2.customRef两个参数  (track,trigger)

<template>

<input type="text" v-model="imputValue">

<h3>{{imputValue}}</h3>

</template>

<script>

import {customRef} from 'vue'

export default {

  setup(){

    let imputValue=custom('请输入')

    function custom(value){
        return customRef((track,trigger)=>{
          return {

            get(){
              track()        //提前通知value回改变    随时做好改变的准备
              return  value  //最后的返回值   这个值是用到模板里面的
            },
            
            set(newValue){
              value=newValue //newValue修改好的值   重新赋值给value
              trigger()      //已经改好了  去通知get()要重新渲染
            }
          }
        })
    }

    //最后return出去
    return {
      imputValue
    }
  }
}
</script>


3.运用customRef写一个反抖

<template>
  <input type="text" v-model="imputValue" />

  <h3>{{ imputValue }}</h3>
</template>

<script>
import { customRef } from "vue";

export default {
  setup() {

    let imputValue = custom("请输入", 500);

    //方法custom接收字段和延迟时间
    function custom(value, times) {

      //定义一个timer,等下要作用于清除定时器
      let timer;

      return customRef((track, trigger) => {
        return {

          get() {
            track();
            return value;
          },

          set(newValue) {
            //清除定时器
            clearTimeout(timer);
            //定时器
            timer = setTimeout(() => {
              value = newValue;
              trigger();
            }, times);
          },
        };
      });
    }

    //最后return出去
    return {
      imputValue,
    };
  },
};
</script>



版权声明:本文为m0_58849641原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。