To serve a YouTube video embed without creating a new Vue page, you can dynamically show the video on an existing page based on the route. One approach to achieve this is by using Vue Router's route parameters or query parameters, along with conditionally displaying the iframe within your component.
Here's a step-by-step guide on how to modify your existing setup to include a YouTube video embed on the IndexPage.vue based on the route:
Step 1: Modify Your Route Configuration
First, decide if you want to use a route parameter (e.g., /video/:videoId) or a query parameter (e.g., /sunshine?videoId=kKEgzTegzXw). For this example, I'll use a route parameter for neat URL structure. You'll need to adjust your route configuration to accept a video ID as a parameter.
// router/index.js or where your routes are defined
const routes = [
{ path: '/', component: () => import('pages/IndexPage.vue') },
{ path: '/sunshine', component: () => import('pages/IndexPage.vue') },
{ path: '/video/:videoId', component: () => import('pages/IndexPage.vue') }, // Added line
{ path: '/:catchAll(.*)*', component: () => import('pages/NotFound.vue') }
];
export default routes;
Step 2: Modify Your Component to Display the Video
Next, adjust your IndexPage.vue component to conditionally display the YouTube video iframe based on the presence of a video ID in the route parameter.
// pages/IndexPage.vue
<template>
<div>
<!-- Your existing page content -->
<!-- YouTube Video Embed -->
<iframe v-if="videoId"
width="853"
height="480"
:src="`https://www.youtube.com/embed/${videoId}`"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen>
</iframe>
</div>
</template>
<script>
export default {
computed: {
videoId() {
return this.$route.params.videoId; // Access the videoId from the route parameter
}
}
};
</script>
Explanation
- Route Parameter in URL: The path
/video/:videoId in the route configuration allows for URLs like /video/kKEgzTegzXw, where kKEgzTegzXw is dynamically part of the URL and represents the YouTube video ID.
- Accessing Route Parameter in Component: Inside the
IndexPage.vue component, the videoId computed property fetches the video ID from the URL's route parameters (this.$route.params.videoId).
- Conditional Rendering: The
v-if="videoId" directive on the iframe ensures that the YouTube embed is only displayed when a videoId is present in the URL.
This setup allows you to display a YouTube video embed directly within an existing page (IndexPage.vue) based on the current route, without needing to create separate pages for each video.