vue 中watch 回调函数和methos中方法的区别

1.vue 中代码
<el-input v-model="searchkey" placeholder="键名" @input="handleInput" clearable style="max-width:300px;"></el-/utils/commonwen文件加下

export function _throttle(fn,wait = 300){
  let last,now
  console.log("last111111111:",last)
  return function(){
    console.log("last:",last)
    now = new Date().getTime()
    if(last && now -last < wait){
      last = now
    }else{
      last = now
      fn.call(this,...arguments)
    }
  }


vue 页面中
import { _throttle } from '@/utils/common' 
methods:{
/*********使用这种方式调用每次都会打印 last111111111111***********/ handleInput () { _throttle(()=>{ this.getList() })() }
}
 watch: {
     /************使用这种方式第一次页面刷新的时候会调用last11111111,改变 searchkey 只会打印last **********************/
     searchkey:_throttle(function(){
       console.log('22222222222')
       this.getList()
     })
  }

  2.综上:
 watch 定义的时候函数已经定义,后面改变searchkey的值只会改变定义过函数内的内容

posted on 2022-10-28 18:05  朝颜陌  阅读(80)  评论(0编辑  收藏  举报

导航