简体   繁体   中英

Why doesn't setting video element srcObject doesn't work inside Vue.js App

Consider the following app (code simplified)

<div id="app">
<video id="my-vid" autoplay></video>
</div>

JS

I am setting document.getElementById("my-vid").objectSrc = stream media stream (after asking the user for the usual user media, etc...) in plain javascript (that is without any vue js property binding).

It doesn't work (browser not displaying media stream, but a console.log still shows a valid MediaStream object.

When i move the video element outside the VueJS app however, it works !

<div id="app">
</div>
<video id="my-vid" autoplay></video>

What could be the reason for that?

I guess the correct way is

document.getElementById("video").srcObject = stream

I used it this way and it works pretty well..

<template>
  <div class="container">
    <video id="videotag" autoplay></video>
  </div>
</template>

<script>
export default {
  name: "video",
  components: {},
  mounted() {
     navigator.getUserMedia = navigator.getUserMedia ||
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia;

        // Start video camera
        navigator.getUserMedia({
                video: true,
                audio: false
            },
            function (stream) {
              document.getElementById('videotag').srcObject = stream
            },
            function (error) {
              console.error(error)
            }
        )
  }
};
</script>

In vue, you should never use document.getElementById() . Anything you can do with document.getElementById() you can do with ref . Try...

<div id="app">
   <video ref="myVid" autoplay></video>
</div>

then in your script, inside Vue...

var me = this;
// Start video camera
navigator.getUserMedia({
        video: true,
        audio: false
    },
    function (stream) {
        me.$refs.myVid.srcObject = stream
    },
    function (error) {
        console.error(error)
    }
)

This is because DOM level id is scoped to the whole page (whole app). From inside your little component, you can't dictate what ids other components might use, and conflicts are possible. Ref only needs to be unique within your component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM