template 部分:
<template>
<van-search
v-model="searchValue"
@input="debounceSearch(onSearch)"
/>
</template>
script 部分:
import { debounce } from 'lodash';
import { Search } from 'vant';
export default {
name: 'input',
component: {
[Search.name]: Search
},
data() {
return {
searchValue: ''
}
},
methods: {
debounceSearch: debounce(function() {
console.log(this);
console.log(this.searchValue);
}, 300)
}
}
结果:
成功拿到 Vue 实例!
注意:
如果使用箭头函数,方法内获取的
this
将指向 window。
因为debounce
里已经apply
了函数的context
,所以对于箭头函数来说,它的context
指向window
,对于匿名函数来说,它的context
是调用时的context
。
错误例子 ( debounce 可以正常执行,但是无法获得 vue 实例):
methods: {
debounceSearch: debounce(() => {
console.log(this);
console.log(this.searchValue);
}, 300)
}
over ~