setData原理:
视图层由webview作为渲染的载体 逻辑层由 JavascriptCore 作为运行环境 WebView 和 JavascriptCore 都是独立的模块,并不具备数据直接共享的通道。 视图层和逻辑层的数据传递通过evaluateJavascript以字符串的方式,evaluateJavascript受多方影响 setData操作过多,导致js线程一直在编译执行,数据到达渲染层的时间延长 setData数据量过大时会增加js脚本的编译执行时间
小程序防抖:
在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时,重新出发定时器。
利用延时器,闭包实现。
search搜索联想,用户在不断输入值时,用防抖来节约请求资源
window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次
小程序防抖函数写法:
function debounce(fn, interval) {
var timer;
var gapTime = interval || 1000; //间隔时间 不传值默认为1000ms
return function() {
clearTimeout(timer);
var that = this;
var args = arguments; //保存arguments setTimeout是全局的 arguments不是防抖函数需要的
timer = setTimeout(function() {
fn.call(that, args);
}, gapTime);
};
}
小程序节流:
规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。 鼠标不断点击触发,mousedown(单位时间内只触发一次) 监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断 做商品预览图的放大镜效果时,不必每次鼠标移动都计算位置
小程序节流函数写法:
function throttle(fn, interval) {
var enterTime = 0; //触发的时间
var gapTime = interval || 300; //间隔时间,如果interval不传值,默认为300ms
return function() {
var that = this;
var backTime = new Date(); //第一次函数return即触发的时间
if(backTime - enterTime > gapTime) {
fn.call(that, arguments);
enterTime = backTime; //赋值给第一次触发的时间 保存第二次触发时间
}
};
}
防抖是将多次执行变为只执行一次,节流是将多次执行变为每隔一段时间执行。
微信小程序tabbar动态居中实现:
<!-- 产品问答分类 -->
<scroll-view v-if='answerClassifyList.length'
scroll-x
scroll-with-animation
:scroll-left="answerScrollLeft"
class='answer-classify px-after-1'>
<view class='dis-flex answer-classify-box'>
<view class='answer-classify-item'
:class="[`answer${index}`, {'answer-classify-item-active': answerSelectedId === item.id}]"
v-for='(item, index) in answerClassifyList'
:key='item.id'
@click='toggleAnswerTab($event, index, item.id)'>
{{item.productQuestionTypeName}}
</view>
</view>
</scroll-view>
// 切换问答分类tab
toggleAnswerTab (e, index, id) {
this.answerSelectedId = id
// 滑动动画处理
const offsetLeft = e.currentTarget.offsetLeft // 元素距离左侧的位置
const windowWidth = wx.getSystemInfoSync().windowWidth // 设备宽度
const query = wx.createSelectorQuery()
query
.select(`.answer${index}`)
.boundingClientRect(rect => {
this.answerScrollLeft = offsetLeft - windowWidth / 2 + rect.width / 2
})
.exec()
}
微信小程序 1rpx 的实现:
/* 1px */
.px-after-1::after {
position: absolute;
content: '';
width: 100%;
left: 0;
bottom: 0;
height: 1px;
background-color: var(--color-border);
-webkit-transform: scale(1, 0.5);
transform: scale(1, 0.5);
-webkit-transform-origin: center bottom;
transform-origin: center bottom;
}
.px-before-1::before {
position: absolute;
content: '';
width: 100%;
left: 0;
top: 0;
height: 1px;
background-color: var(--color-border);
-webkit-transform: scale(1, 0.5);
transform: scale(1, 0.5);
-webkit-transform-origin: center top;
transform-origin: center top;
}