乐趣区

关于vue.js:Vue回调方法内获取不到当前组件this元素的解决方案

vue 页面应用 addEventListener,对页面元素增加事件监听,在 addEventListener 办法外部无奈获取 data 定义的变量值。

编写 videoList.vue 页面,页面代码如下所示。

<template>
    <div class="container">
        <div class="video-list">
            <div class="remote-video">
                <div class="remote-video-item" v-for="pull in pullStreamList">
                    <video controls="controls" controlslist="nodownload" :disablePictureInPicture="true"
                           autoplay="autoplay" :id="`remote-video-${pull.id}`">
                        <source src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
                    </video>
                </div>

            </div>

        </div>
    </div>
</template>

<script>
    export default {
        name: "test",
        data(){
            return{pullStreamList:[],
            }
        },
        mounted:function () {
            let _this = this;
            _this.pullStreamList.push({"id":"00001","name":"test00001"});

            let timer = setInterval(function () {_this.removeRemoteVideo('00001');
                clearInterval(timer)
            },10)
        },
        methods:{removeRemoteVideo:function (pullId) {let newRemoteVideo = document.getElementById("remote-video-" + pullId);
                console.log("newRemoteVideo",newRemoteVideo);
                console.log("_this.pullStreamList before", this.pullStreamList);
                newRemoteVideo.addEventListener("play",function () {console.log("_this.pullStreamList after", this.pullStreamList);
                })
            }
        }
    }
</script>

页面输入_this.intervalList after 的值是为 undefinded,然而在_this.intervalList before 输入的变量的确有内容的,两个 this 示意不同的对象。

退出移动版