跳到主要内容

vue

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

cmputed 注册实现

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

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

methods 注册实现

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

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

指令注册实现

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

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