Attempting to manipulate Plyr through API using Vue.js

Introduction

I have integrated Plyr as a video wrapper on my website for controlling the video player through its API when triggered by a debounce function.

Essentially, when a new YouTube video ID is provided, I aim to replace the existing video with the new one and autoplay it accordingly. This functionality will later be incorporated into another component on the website.

The Challenge

I am encountering difficulty in manipulating the player via the API, resulting in an inability to utilize Plyr functions or make any modifications to its behavior after Vue.js completes its tasks.

In the updateVideo function, I attempt to play the video using player.play(), but this action triggers the following console error:

Cannot read property 'play' of undefined

I have consulted the documentation in an effort to resolve this issue, yet I remain stuck at this point.

YouTube.vue

<script>
    import Plyr from 'plyr'
    import axios from 'axios'
    import Swal from 'sweetalert2'
    import _ from 'lodash'

    const Toast = Swal.mixin({
        toast: true,
        position: 'center',
        showConfirmButton: false,
        timer: 3000
    })

    export default {
        data() {
            return {
                // bTqVqk7FSmY
                movieName: 'JL3b_fewO08',
            }
        },
        mounted() {
            const player = new Plyr('.yt-player');
        },
        methods: {
            updateVideo: function() {
                const player = new Plyr('.yt-player');
                player.play(); // This throws an error
                player.volume = 0.5;
            },
            debounceVideo: _.debounce(function() {
                this.updateVideo();
            }, 700)
        },
    }
</script>
<template>
    <div class="my-10 mx-auto pl-10">
        <form class="mb-3">
            <input type="text" v-model="movieName" @input="debounceVideo" class="border-2 p-2 w-full" placeholder="Please specify a movie name" data-city-name>
        </form>
        <div class="w-full">
            <div class="yt-player" data-plyr-provider="youtube" v-bind:data-plyr-embed-id="movieName"></div>
        </div>
    </div>
</template>

I am facing challenges in controlling the video player as per the API specifications.

Moreover, I explored vue-plyr but found that it does not align with my requirements and presents similar issues.

Your assistance would be greatly appreciated as always.

Answer №1

The reason for this issue is due to losing the original reference to the Plyr instance. A better approach would be to store the new Plyr instance in a class member like this:

this.player = new Plyr('.yt-player');
.

Here is an updated version of your code that outlines the necessary steps:

  1. Add a new key to your data,
  2. Assign the newly created instance using this.player = new Plyr(...), and
  3. Reference the player instance by using this.player:

export default {
    data() {
        return {
            movieName: 'JL3b_fewO08',

            // Create a key to store the new Plyr instance
            player: null,
        }
    },
    mounted() {
        // Save the instance in data
        this.player = new Plyr('.yt-player');
    },
    methods: {
        updateVideo: function() {
            // Access the Plyr instance with this.player
            this.player.play();
            this.player.volume = 0.5;
        },
        debounceVideo: _.debounce(function() {
            this.updateVideo();
        }, 700)
    },
}

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

Making adjustments to a row in the free jqGrid is a breeze with the ability

Using free jqGrid 4.12.1, I aim to incorporate functionality for adding, editing, and deleting rows in the grid with server-side calls for each operation. Below is the implementation of editurl and 'actions' formatter, { name: "actions", wi ...

Understanding the reach of the index in a callback function for jQuery UI dialog

I'm currently in the process of developing a dynamic function that can create a Dialog widget along with buttons. These buttons are generated based on a list of label and callback function pairs that are provided as an argument to the generating funct ...

The Vuetify combobox item template fails to update when coupled with Vuex

I have encountered an issue with the Vuetify combobox while using item and selection slots. The problem arises when I update my Vuex store by checking or unchecking items. Everything works fine in terms of updating for the selection slot, but if I remove a ...

The drop-down menu fails to appear when I move my cursor over it

#menu { overflow: hidden; background: #202020; } #menu ul { margin: 0px 0px 0px 0px; padding: 0px 0px; list-style: none; line-height: normal; text-align: center; } #menu li { display: inline-block; } #menu a { display: block; position: relative; padding ...

Sending an empty object from postman in form-data to a node.js server is causing issues

Despite searching extensively, I have yet to find a solution to my issue that has been asked numerous times before. index.js file const express = require("express"); require("dotenv").config({ path: ".env", }); const PORT = ...

Enhance my code to eliminate repetitive elements

Check out this unique plant array: export const uniquePlants = [ { name: 'monstera', category: 'classique', id: '1ed' }, { name: 'ficus lyrata&ap ...

Triggering a page refresh with Framework7

Currently, I am in the process of developing a compact webapp utilizing the framework7 split-view-panel example. This eases navigation by providing a left-hand navigation bar that, upon clicking, loads a URL in the right-hand panel. However, I have notice ...

Leveraging NextJS to retrieve a complex array of objects from MongoDB through the use of mongoose and getServerSide

My goal is to retrieve an array of objects from MongoDB, utilizing mongoose and SSP. The only challenge I am facing is that all ObjectIds need to be converted into strings. Currently, I am handling it in the following manner: export async function getSe ...

The module for the class could not be identified during the ng build process when using the --

Encountering an error when running: ng build --prod However, ng build works without any issues. Despite searching for solutions on Stack Overflow, none of them resolved the problem. Error: ng build --prod Cannot determine the module for class X! ...

Issue with toggling options in q-option-group (Vue3/Quasar) when using @update:model-value

I'm a newcomer to the world of Quasar Framework and Vue.js. I recently tried implementing the q-option-group component in my simple application but encountered an issue where the model-value and @update:model-value did not toggle between options as ex ...

Exploring the integration of React Suspense boundary to handle data fetching from API following specific triggers

Hello, I am relatively new to React and JS. I am currently working on implementing the React Suspense boundary for a component that requires fetching data from my backend API. I followed an example that provided functions like fetchData and wrapPromise [h ...

What is the best way to incorporate a highlighting bar below a link for emphasis?

How can I create a highlight effect above a link in the status bar, similar to what is seen on Fiddle sites? The highlight should remain above the active link and move to the link the mouse hovers over. Here is an example image of what I am trying to achie ...

Removing children does not work properly; it only removes half of them

Why am I unable to remove all children if I delete half of them in this code? I keep getting an error saying child is not defined, even though I have declared it. Each node in my code has children spheres (nodes) and edges (lines), but when I try to dele ...

Encountering ERR_TOO_MANY_REDIRECTS while using Nuxt 3 and navigateTo

I am facing an issue with my pagination system that is linked to the format /catalog/[slug]?page=1 in the address bar. I can browse different catalog pages by manually entering the page number like ?page=1 in the address bar. I am monitoring the page param ...

Creating a dynamic navbar with Python (Django), HTML, CSS, and Javascript for a fully responsive

I am currently utilizing a guideline to develop a responsive navbar that adapts its layout based on the screen size. It will display elements in a dropdown list for smaller screens, as opposed to an inline layout used for larger screens. Here is a snippet ...

JavaScript Function that Automatically Redirects User or Updates Text upon Clicking "Submit" Button

Looking to create JavaScript functionality that directs users back to the homepage after submitting their name and email. The process should follow these steps: 1.) User clicks "Request a Brochure..." https://i.sstatic.net/KqH2G.jpg 2.) A window opens in ...

The Vue router issues a cautionary message indicating a lack of match for the dynamic route: Location path "/test" not found

I successfully added a route dynamically, but I am encountering the following warning message. "No match found for location with path "/test". Check out the Code Sandbox demo for reference: https://codesandbox.io/p/github/eguvenc/routertes ...

Utilizing external JavaScript functions within a webpage

When working with embedded javascript, I have defined specific functions within to construct a table: <% function createCollectionTableRow(col) { %> <tr> <td> <a href="/<%= database %>/collections/<%= collections[ ...

Discovering the selected row with jqueryIs there a way to locate

There is a table with rows and a button that allows you to select a row: <table id="mytable" class="table-striped"> <tbody> <tr id="1"><td>Test1</td></tr> <tr id="2"><td>Test2</td>& ...

Unexpected geometry encountered with TopoJson and ChartGeo/ChartJS integration

I have successfully used TopoJson and ChartJS to create a map of the UK. However, I am now facing difficulty in drawing two squares off the west coast of GB. Here is my custom-written TopoJson data: const topoData = { type: "Topology", a ...