1>vue頁面
data() { let validcodeName = (rule, value, callback) => { let parmas = { name: value, rule: rule, callback: callback }; this.getProjectByName(parmas); }; return { rules: {
//注意,不管是防抖還是節流,都得在這里去加,不能加在validcodeName里面
demandName: [{ required: true, validator: this.debounce(validcodeName, 1000), trigger: 'change' }],
}
}
methods: {
...mapActions(['getFunctionByName']),
//發送請求
sendGetFunctionByName(rule, value, callback) {
let parmas = {
name: value,
projectId: this.$route.query.id,
type: '需求',
rule: rule,
callback: callback
};
this.getFunctionByName(parmas);
},
//防抖
debounce(fn, delay) {
// 記錄上一次的延時器
var timer = null;
var delay = delay || 200;
return function() {
var args = arguments;
var that = this;
// 清除上一次延時器
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(that, args);
}, delay);
};
},
//節流
throttle(fn, wait) {
var timer = null;
return function() {
var context = this;
var args = arguments;
if (!timer) {
timer = setTimeout(function() {
fn.apply(context, args);
timer = null;
}, wait);
}
};
},
actions
actions: { getProjectByName(context, data) { console.log("22", data); let params = { name: data.name }; SourceMirror.getProjectByName(params).then(res => { if (res.data.data === false) { data.callback(new Error("項目名稱已重復")); } else if ( data.name == undefined || data.name == "" || data.name == null ) { data.callback(new Error("請輸入項目名稱")); } else { data.callback(); } context.commit("verifProjectByName", res.data.data); }); } },
2>場景,blur的input離開就發送修改接口,但是與頁面上其他事件沖突,必須請求完了才允許點,這時候就需要防抖了
<input :class="{'isFocus':isFocus|| detail.expectHours}" id="inputRef" :disabled="saveHandleStatus==4" v-model="detail.expectHours" @focus="isFocus= true" @blur="debounce(hoursBlur,2000)()" // class="hours" :placeholder="placeholder" />
@blur="debounce(hoursBlur,2000)()" //注意這個寫法,不這樣寫,不執行
