跳到主要内容

vue

2024年03月12日
柏拉文
越努力,越幸运

computed 注册使用

<template>
<div id="app">
<button @click="debounce">测试</button>
</div>
</template>

<script>
import {debounce} from "./utils/index.js";
export default {
name: 'App',
computed:{
debounce(){
return debounce(this.handler, 1000);
}
},
methods: {
handler() {
console.log("张文强");
},
},
}
</script>

methods 注册使用

<template>
<div id="app">
<button @click="debounce">测试</button>
</div>
</template>

<script>
import {debounce} from "./utils/index.js";
export default {
name: 'App',
methods: {
debounce:debounce(function(){
this.handler();
},3000),
handler() {
console.log("张文强");
},
},
}
</script>

vue 指令注册使用

directive>debounce>debounce.js
function debounce(fn, wait) {
}
export default {
bind(el, binding) {
/**
*@description: 指令传参数和指令不传参数的情况
*/
if (binding.value instanceof Array) {
const [func, time = 500] = binding.value;
el.execFun = debounce(func, time);
} else {
el.execFun = debounce(binding.value, 500);
}
el.addEventListener("click", el.execFun);
},
unbind(el) {
el.removeEventListener("click", el.execFun);
delete el.menuFun;
},
};
directive>debounce>index.js
import Vue from 'vue'
import debounce from "./debounce";
const install = function(Vue) {
Vue.directive("debounce", debounce);
};
if (window.Vue) {
window["debounce"] = debounce;
Vue.use(install);
}
debounce.install = install;
export default debounce;
<template>
<div id="app">
<button v-debounce="[() => handler('张文强'), 3000]">测试</button>
</div>
</template>

<script>
import debounce from "./directive/debounce";
export default {
name: "App",
directives: {
debounce,
},
methods: {
handler() {
console.log("张文强");
},
},
};
</script>