Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for setting the srcObject using VueJS

Setting the "src" attribute of the html video element does not work with Vue.js and Vuex:

<video id="myVideoEl" :src="myStreamSrc" autoplay="autoplay">

myStreamSrc is a computed value and is set in a mutation by an event handler:

AddStream: function (state, plMyStream) {
  state.myRTCPeerConnection.addStream(plMyStream)
  state.myStreamSrc = plMyStream
}

When I run my application with that code, I get the following error:

HTTP “Content-Type” of “text/html” is not supported. Load of media resource http://localhost:8080/[object%20MediaStream] failed.

When I do the following:

state.myVideoEl = document.querySelector('#myVideoEl')
state.myVideoEl.srcObject = payloadWithMyStream

I do not get any error and the stream is shown. The problem is, I can not use the working code snipped because the referenced elements are added later to the DOM. This code snippet does not work when I bind the html video element in a div with a v-if Vuex.js attribute. Then I just get "undefined" as a result (because the div element with the video element did not exist on page load).

Is there a difference between setting the srcObject and setting the src attribute? I thought that when I set srcObject the video element will have a src attribute, but it does not.

Is it possible to set the srcObject in the video html attribute?

For more info, please visit my theard in the Vue.js forum: https://forum.vuejs.org/t/reference-elements-when-they-rendered-with-v-if/16474/13

like image 917
La0x1 Avatar asked Aug 25 '17 19:08

La0x1


2 Answers

srcObject is modifier not a html attribute, so you need to write

<video :srcObject.prop="myStreamSrc" autoplay/>

See answer from Priansh Shah for a 2019 update.

like image 84
Georgi Jhangiryan Avatar answered Sep 27 '22 16:09

Georgi Jhangiryan


Posting an updated solution for newer versions of Vue in case anyone comes across this and runs across the same errors I did.

Updating for 2019:

<video :src-object.prop.camel="stream">

The first change is to bind to srcObject using v-bind, here’s an example with the shorthand:

<video :srcObject.prop="stream">

However srcObject is camel cased so in HTML it just becomes srcobject (lowercase) which is considered a different property and so won’t fire the video.

If you’re using Vue < 2.1, you’ll have to fire it manually using document.getXXXXX(...).srcObject = stream.

But if you’re using Vue v2.1+ you’re in luck as there is now an API modifier for this as well:

<video :src-object.prop.camel="stream">

.camel converts kebab-case to camel case, so to get srcObject we do the reverse and get src-object.camel. Combining this with .prop and v-bind we get the above syntax.

like image 20
cuuupid Avatar answered Sep 27 '22 15:09

cuuupid