Utilizing HTML 5 Video and the src Attribute in Vue Components

I am facing an issue with loading an HTML 5 video dynamically on my page. I am using vue for this purpose and in my js controller, I set a variable containing the video path. Here is how I am trying to use the variable in my page:

<video width="450" controls>
    <source v-model="controller.var" v-bind:src="var" type="video/mp4">
</video>

Even though the var is correctly set with the URL, the video player does not load the video. Can someone tell me what I might be missing?

Appreciate any help!

Answer №1

By simply adding the key attribute containing the URL of the source to the video element, you can ensure that both the video and its source are updated whenever the URL changes:

<template>
  <video
    :key="src"
    :width="width"
    controls
  >
    <source
      :src="src"
      :type="type"
    >
  </video>
</template>

<script>
  export default {
    data() {
      return {
        src: 'https://www.example.org/video.mp4',
        type: 'video/mp4',
        width: 450
      }
    }
  }
</script>

This feature enables seamless replacement of a dynamic video + source pair.

Answer №2

Initially, it is uncertain whether you are utilizing var in your template or not. If indeed you are using it, Vue will generate a warning in the template.

  • Avoid using a JavaScript keyword as a property name like "var" in the expression :src="var"

Furthermore, altering the source element dynamically is not possible.

According to the HTML5 specification,

Modifying a source element and its attribute dynamically when the element is already inserted in a video or audio element will not result in any changes. To adjust what is being played, simply utilize the src attribute on the media element directly, maybe leveraging the canPlayType() method to choose from available resources. Generally, manually manipulating source elements after the document has been parsed is an overly complex approach.

Hence, bind your data to the src attribute of the video element.

<video width="450" controls :src="video"></video>

console.clear()

new Vue({
  el:"#app",
  data:{
    video: "https://www.w3schools.com/tags/movie.mp4"
  },
  methods:{
    changeVideo(){
      this.video = "http://techslides.com/demos/sample-videos/small.mp4"
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a6c6f7f5a283428342c">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <video width="450" controls :src="video"></video>
  <div>
    <button @click="changeVideo">Change</button>
  </div>
</div>

Answer №3

To dynamically alter the src attribute, you can modify it and then trigger the new source to load using the .load() method.

new Vue({
  el:"#app",
  data:{
    src: ""
  },
  methods:{
    changeVideo(newSrc){
      this.$data.src = newSrc;
      //Force video load.
      var vid = this.$refs.video;
      vid.load();

    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9afacbc99ebf7ebf7ef">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <video width="450" controls :src="src" ref="video"></video>
  <div>
    <button @click="changeVideo('http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4')">Change1</button>
        <button @click="changeVideo('https://www.w3schools.com/tags/movie.mp4')">Change2</button>
  </div>
</div>

Answer №4

Consider assigning the complete source as a variable within the controller script.

<video controls autoplay>
  {{{ src }}}
</video>

new Vue({
  el: '#app',
  data: {
    src: '<source src="#url" type="video/mp4">'
  }
})

Answer №5

For those who are curious, here is an equally impressive solution to consider

<source v-if="src" :src="src" :type="type">

found at this GitHub link

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

When the submit button on the signup form is pressed, two distinct actions are activated to achieve specific outcomes

I am seeking assistance in implementing code that will trigger the following action: Upon clicking the 'Submit' button on a signup form after the subscriber enters their email address and name, the signup page should reload within the same tab wi ...

How to load a table file in JavaScript synchronously

I came across this particular method for accessing a local text file. However, I am facing an issue as I do not want the file to be read asynchronously. My goal is to have the function read the file and return the output as a string variable instead. The ...

Utilizing Various Perspectives in Angular with the ng-view Directive

Can anyone assist me with a challenge I'm facing regarding views? While this is a hypothetical scenario and there's no code available to review... Let's imagine a simple site with three routes: /signin /users /users/:id Upon accessing t ...

What is the method for retrieving the dev server proxy target from within the application?

Currently, I am utilizing an iframe within the application. However, I am facing a challenge in proxying its src via the development server. As a workaround, I have implemented the following code: const origin = process.env.NODE_ENV === 'production&ap ...

Having trouble getting Three.js JSON models to cast shadows properly?

Recently, I've been experimenting with blender exported models in Three.js. I have successfully imported a model and observed how light interacts with the object. While a directionalLight is illuminating the front-facing parts, I'm facing an issu ...

Utilizing JavascriptExecutor in Powershell

I've been working on a series of Powershell scripts that utilize the Selenium Webdriver. Now, I am looking to incorporate some JavaScript functionality into one of them. However, I am struggling to understand how to get the syntax right. I tried ada ...

Stylish Navigation Menu Logo/Site Name

Currently in the process of upgrading my website and I have my website name included as part of my menu, as opposed to a logo. This has been an easy solution that has worked well for me. For mobile screens, the template I purchased includes a slicknav men ...

After refreshing the page, the console log within the React useEffect function ceases to function

Incorporating the 'useEffect' function to fetch data and store it in the 'ratings' array has proven successful. However, there seems to be an issue when attempting to iterate through the elements of the 'ratings' array for log ...

Using Javascript to delete an HTML list

Currently, I am working on a webpage that includes notifications along with options to mark them as read individually or all at once. However, when attempting to use my loop function to mark all notifications as read, I noticed an issue. let markAllAsRead ...

Utilizing v-data-iterator in Vuetify to display data fetched from an API in a table

After a long day of searching and experimenting, I've finally arrived here. Initially, I attempted to create a simple table with 2 columns using Row and iterate over the object to populate the left column with its keys. However, I hit a roadblock when ...

"Master the art of creating a curved circular arrow using a combination of HTML, SVG, D3.js

I am looking to design an SVG circle with a fading stroke that blends into the background and features an arrow at one end. The goal is for the ring to fade out completely right above the arrow, similar to the visual reference provided in the image.view ex ...

Leveraging set() for computed values accurately in Vue

I'm currently facing an issue with setting a computed property that happens to be an array. Within my Vue component, I have the following computed property: posts: { get () { if ( this.type == 'businesses' || this.type == 'busine ...

Generating a list of items to buy using a JSON document

So here's the json file I'm working with: [ {"task":"buy bread","who":"Sarah","dueDate":"2023-10-18","done":false}, {"task":"clean car","who":"David","dueDate":"2023-08-30","done":true}, {"task":"write report","who":"Jenny","dueDate":"2023-09 ...

Tips for personalizing text and icon colors in the TableSortText element of Material-ui

My Goal: I aim to empower users with the ability to apply customized styles to my EnhancedTable component by utilizing a styles object containing properties like headCellColor, headCellBackgroundColor, bodyCellColor, bodyCellBackgroundColor, and more. The ...

Tips for real-time editing a class or functional component in Storybook

Hey there, I am currently utilizing the storybook/react library to generate stories of my components. Everything has been going smoothly so far. I have followed the guide on https://www.learnstorybook.com/react/en/get-started and added stories on the left ...

Verification of email address is required, emails must be unique and not duplicated

I am working on validating email addresses to ensure they are not repeated. So far, I have successfully pushed them from the server into an array using regex for validation. What steps should I take next to compare and further validate these emails? ...

Invoke the parent's trigger method from a child component nested within a router in Quasar Framework (Vue)

I've configured my nested routes in the router using the Quasar framework (vue 3) like this: const routes = [ { path: "/", component: () => import("layouts/myLayout.vue"), children: [ { path: "&q ...

HeaderView in Angular Framework

When exploring the best practices for organizing an AngularJS structure, I came across the recommendation to implement partial views as directives. Following this advice, I created a directive for my app header. In my specific header design, I included a ...

Updating the styles of React Native components using stylesheets

I've created a unique React component with the following structure: import { StyleSheet } from 'react-native'; import { Input, Item } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import { ...

Guide to adding a Scrollable Navbar

Is the term "scroll bar" really accurate? I want to create a scrollable feature where users can easily select a city using their mouse wheel (or swipe on a smartphone) and then choose from possible cities within that country in a second window. Something s ...