问题已解决。小程序里的视图层和逻辑层本身就是独立运行的,我原来的写法是在逻辑层实现,那么把这个操作放进视图层里运行即可解决问题。使用BindingX实现,文档:https://alibaba.github.io/bindingx/guide/cn_introduce。
简单案例:
// uniapp nvue
<template>
<view class="wrapper">
<list class="list" ref="list" :style="{height:`${appHeight}px`}" :show-scrollbar="false">
<cell class="item" v-for="i in len" :key="i">
<text>{{ i }}</text>
</cell>
</list>
<view class="scrollBar" :style="{height:`${appHeight}px`}">
<view class="bar" ref="scrollBar"></view>
</view>
</view>
</template>
<script>
const Binding = uni.requireNativePlugin('bindingx')
export default {
data() {
return {
len:100
}
},
mounted() {
this.$nextTick(()=>{
let appHeight = this.appHeight,
listHeight = (95 + 5) * this.len;
Binding.bind({
anchor: this.getEl(this.$refs.list),
eventType:'scroll',
props:[
{
element: this.getEl(this.$refs.scrollBar),
property: 'transform.translateY',
expression: `y / ${listHeight} * ${appHeight}`
}
]
})
})
},
methods: {
getEl(el) {
if (typeof el === 'string' || typeof el === 'number') return el;
if (WXEnvironment) {
return el.ref;
} else {
return el instanceof HTMLElement ? el : el.$el;
}
},
},
computed:{
appHeight(){
return this.$store.state.appHeight;
}
}
}
</script>
<style>
.item{
color: white;
border-top-width: 5px;
height: 95px;
background-color: #007AFF;
align-items: center;
justify-content: center;
}
.scrollBar {
position: fixed;
right: 0;
top: 0;
z-index: 10;
width: 20px;
}
.bar {
position: absolute;
background-color: #232323;
width: 15px;
right: 3px;
border-radius: 20px;
height: 60px;
}
</style>