uniapp 监听页面滚动

212 阅读1分钟

store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        meScrollY: 0
    },
    mutations: {
        setMeScrollY(state, value) {
            state.meScrollY = value;
        }
    }
})
export default store

u-scroll-view在滚动组件页面:

<scroll-view :id="viewId" :scroll-top="scrollTop" :scroll-with-animation="scrollAnim" @scroll="scroll">
    XXXX
</scroll-view>
<button @click="toTopClick">返回顶部</button>

scroll(e) {
    // 更新滚动坐标
    this.$store.commit('setMeScrollY', e.detail.scrollTop)
},
toTopClick() {
    // 更新滚动坐标
    this.$store.commit('setMeScrollY', 0)
}

外部组件监听是否滚动:

<u-scroll-view>
    <view>
        {{0===meScrollY ? '滚动到顶部啦' :'滚动到其他为止了'}}
    </view>
</u-scroll-view>
                
computed: {
    meScrollY() {
        return this.$store.state.meScrollY;
    }
}