Vue监听页面滚动

Vue监听页面滚动

直接上代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="index.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<style>
    body{
        width: 100%;
        height: 9000px;
    }
    #app{
        position: fixed;
    }
</style>
<body>
<div id="app">
    {{msg}}
</div>
</body>
<script>
    var app= new Vue({
        el:"#app",
        data:{
            msg:"0"
        },
        mounted () {
            var that = this;  //由于mounted本身是个函数,所以function(){}中的函数this指向了mounted    						
            window.onscroll = function () {
                var scrcllTop = document.documentElement.scrollTop || document.body.scrollTop
                console.log(scrcllTop)
                that.msg = scrcllTop
            }
        },
    })
</script>
</html>

总结:

Vue实例生命周期图

20200923124057696

钩子函数 mounted

类型:function

详细:实例进行到了运行阶段

var app = new Vue({
    el:"#app",
    data:{
        
    },
    mounted (){
        window.onscroll = function(){
            var that = this;
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            that.msg = scrollTop
        }
    },
})
posted @ 2021-05-11 21:03  青鷣丶  阅读(559)  评论(0编辑  收藏  举报