"Encountered an issue: Unable to assign value to property 'srcObject' as it is null in Vue.J

Utilizing vue.js in combination with the element-ui library, I am facing a challenge where I need to display a dialog component for accessing the camera and user's audio. However, an error is being thrown in the console:

TypeError: Cannot set property 'srcObject' of undefined"

The process begins by calling the mounted instance to capture video and audio data from the user, and then, in the show dialog function, I retrieve this data.

Below is the code snippet:

    <template>
        <div class="main-background">
        <el-main>
                <el-row class="opt" style="top: 11%">
                    <el-col :push="16" :span="2">
                        <el-button v-show="false" @click="quickMeeting" :style="shadow" type="primary">
                           <i class="el-icon-video-camera"></i> Quick Meeting
                        </el-button>
                    </el-col>
                   
                </el-row>
                <el-dialog id="video-dialog" :visible.sync="dialogVisible" style="padding: 0;margin:0">
                    <div id="dialog-video" style="backgroud-color: #fff;width:100%;height:100%;" v-show="turnonVideoCamera">
                        <video  autoplay ref="videoBackup" style="position: relative;width:100%;height:100%;"></video>
                    </div>
                    
                </el-dialog>
            </el-main>
        </div>
      
</template>

<script>
export default {
    name: "index",
    data() {
        return {
           
            roomNumber: '',
            dialogVisible: false,
            localStream: null,
            videoDevice: null,
            
        }
    },
    methods: {
        async _initMethod(){
            console.log("xd")
            const devices = await navigator.mediaDevices.enumerateDevices();
            const videoDevices = devices.filter(device => device.kind === 'videoinput');
            this.videoDevice = videoDevices.length >0?videoDevices[0]:null;

            this.localStream = await navigator.mediaDevices.getUserMedia({
                video: this.videoConf,
                audio: true,
            });


        },
        quickMeeting() {        
            this.showDialog();
        },
        
        jump(){
            sessionStorage.setItem('joinName', this.joinName);
            sessionStorage.setItem('turnonVideoCamera', this.turnonVideoCamera);
            sessionStorage.setItem('turnonMicrophone', this.turnonMicrophone);
            this.$router.push('/meeting/'+ this.roomNumber);
        },
        showDialog(){
            this.dialogVisible = true;
            this.$nextTick(function() { 
                console.log("xd")
                this.$refs.videoBackup.srcObject = this.localStream; 
            })
        },
       
    },
    mounted(){
        this._initMethod();
        console.log("xd")
    },
    computed:{
        videoConf: function(){
            return  {
                deviceId: this.videoDevice.deviceId,
                width: 1920,
                height: 603
            };
        }
    }
}
</script>

Answer №1

In order to properly reference the component object within the callback of your $nextTick function, you should utilize Arrow functions.

openPopup(){
 this.popupVisible = true;
 this.$nextTick(() => { // using an arrow function
    console.log("hello")
    this.$refs.imagePreview.src = this.imageUrl; 
  })
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular: Dividing a web page with its individual controller

Exploring Angular Composition An individual new to Angular is eager to implement the concept of "composition," where the main page contains various smaller web page components. Starting off with just a Header section that binds perfectly. <html> &l ...

What is the best way to modify the display of a specific section on a page in VueJs 3?

I have three main sections on my webpage, and I am looking to change the view for just one section: <template> <div id="main"> <div id="scene"> <scene/> </div> < ...

The problem of transparency in Three.js when using PointClouds and textures

Seeking assistance with a project involving two PointCloud objects, each representing a specific structure and texture. One of them should be clickable while the other should not. Let's refer to them as P1 and P2, respectively. P1 is set up using a T ...

Searching for variables within files using Node.js and constructing an object from the results

Trying to figure out how to streamline this process. Here's the directory structure I'm working with: src/ modules/ clients/ i18n/ en-US.ts tasks/ i18n/ en-US.ts So, ea ...

Conceal a section of a container with the click of a button within a WordPress Plugin

I am currently utilizing a Wordpress plugin known as contact form 7 to construct an email list for an upcoming website project. The client has specifically requested that we avoid using services like mailchimp due to their preference of not sending ANY ema ...

When the page loads, sorting by numbers will automatically occur without requiring a click event

Hey there! I've got a modal set up for displaying event details like the one shown in this image: https://i.sstatic.net/73xTW.png Within this modal, users have the option to accept, reject, or leave events pending. In our API, the status values corre ...

Tips for importing JSON data from a file into a jQuery variable?

I have a JSON document that contains: { "data": [{ "red": "#f00", "green": "#0f0", "blue": "#00f", "cyan": "#0ff", "magenta": "#f0f", "yellow": "#ff0", "black": "#000" }] } My goal is to ret ...

Learn the process of uploading a file using FormData alongside multer in node js. Experience the issue of receiving undefined in req.file and { } in req.body

Is there a way to successfully upload a file using FormData along with multer in Node.js? I seem to be encountering issues as req.file shows undefined and req.body displays {}. Check out the HTML code snippet below: <input type="file" name=&q ...

How can I troubleshoot the overflow-y problem in a tab modal from w3 school?

https://www.example.com/code-sample overflow: scroll; overflow-y: scroll; When I type a lot of words, they become hidden so I need to use overflow-y=scroll. Despite trying both overflow: scroll; and overflow-y: scroll;, I have been unable to achieve the ...

What steps are necessary to create the accurate dist files?

I am working on a Vue project that was not initialized using vue-cli. Recently, I ran the following command: npm run build However, the output files are not in the correct format; they appear disordered. How can I generate better dist files similar to w ...

Update the appearance of an element in real-time using VUEJS

I am trying to use VueJS to dynamically change the position of a div. In the data function, I have a variable called x that I want to assign to the top property. However, the code I wrote doesn't seem to be working. Here is what it looks like: <tem ...

How can we efficiently validate specific fields within arrays and objects in express-validator by utilizing the body() method?

I have organized my field names in an array as follows: const baseFields = [ 'employeeNumber', 'firstName', 'lastName', 'trEmail', 'position' ]; These are the only input fields I need to focus on for valid ...

Adjusting the Aspect Ratio of an Embedded YouTube Video

<!DOCTYPE HTML> <head> <style> body { overflow: hidden; margin:0; } </style> </head> <body> <iframe id="video" src="https://www.youtube.com/embed/U4c9bBeUe4M?modestbranding=1&sh ...

Using Gulp Filter in Conjunction with Source Maps

My initial query was similar to this one here, but it led me to delve deeper into research and explore a new approach. Essentially, I am attempting to consolidate all my .js and .coffee files within a single gulp.src() object and execute relevant tasks ba ...

Tracking progress within an HTML table

I am facing an issue with a table that is designed to display progress bars for each method or task stored in the database. These progress bars are determined by two dates: the startDate and endDate. However, I have noticed that the progress bar only funct ...

When attempting to display an image in React Native by fetching the image file path from a database, the image does not

I am working with a database that has a table for courses. https://i.sstatic.net/PSNWY.png My goal is to display images by using the image path stored in the image column of the table. In my React Native application, I have a component for listing carts ...

Activate a Python Selenium function to click on a datepicker element

Looking for some help with selenium as I navigate my way around passing values into a form. While I've managed to successfully input values into regular text boxes, I'm struggling with the onclick datepicker function. Here's what I have so f ...

Using Vue to perform multiplication on data table entries

Is there a way I can use Vue.js to multiply values in a table? The values provided are for 100g of the product. For example, if I input 200g, I would like the values to double: 318kcal, 12 fat, 48 carbs, 8 protein, and 2% iron. Similarly, inputting 50g sho ...

Supplier for a module relying on data received from the server

My current component relies on "MAT_DATE_FORMATS", but I am encountering an issue where the "useValue" needs to be retrieved from the server. Is there a way to make the provider asynchronous in this case? export const MY_FORMATS = { parse: { d ...

Preserving Previous Values in Vuetify Select

Experience a unique way of handling Vueitfy selections with this code snippet: <v-select label="..." autocomplete append-icon="search" :items="plots" item-value="id" item-text="plotHeader" v-model="selectedPlot" v-on:change="loadPlotInforma ...