前人栽树,后人乘凉
vue3.x的时代,已然来临。相对于vue2.x的版本,是有很大的变化出入。
在此,仅记录vue3.x使用lodash的操作
一、安装
npm i lodash -S
or
yarn add lodash -S
二、使用
2.1 vue3.x使用
在需要使用lodash的组件内进行引入
import _ from 'lodash';
setup(){
// 防抖
const _debounce = _.debounce(function() {
// ....
console.log("防抖");
}, 2000);
// 节流
const _throttle = _.throttle(function() {
// ....
console.log("节流");
}, 2000);
}
用例示范:
<van-button type="warning" @click="addShopping">加入购物车</van-button>
<van-button type="danger" @click="buyNow">立即购买</van-button>
import _ from 'lodash';
import { useRouter } from "vue-router";
import { Toast } from "vant";
setup(){
const router = useRouter();
// 防抖
const _debounce = _.debounce(shoppingCart, 200);
// 异步操作函数
const shoppingCart = (path) =>{
addCart().then(res => {
Toast.success("添加成功!");
if (path) {
let timeout = setTimeout(() => {
router.push(path);
clearTimeout(timeout);
}, 1000);
}
})
}
// 加入购物车
const addShopping = () => {
let path = '/shopcart'
_debounce(path);
}
// 立即购买
const addShopping = () => {
_debounce();
}
return {
addShopping,
buyNow
}
}
2.2 vue2.x使用
用例示范:
<van-button type="warning" @click="addShopping">加入购物车</van-button>
<van-button type="danger" @click="buyNow">立即购买</van-button>
import _ from 'lodash';
import { Toast } from "vant";
...
created() {
// 此处声明
this._debounce = _.debounce(this.shoppingCart, 200, false);
},
methods:{
shoppingCart(path) =>{
// ... 此处执行具体逻辑
console.log('path',path);
},
addShopping(){
// 此处使用
this._debounce();
}
},
unmounted() {
// 此处清除
this._debounce.cancel()
},
...