Interactive carousel item selection based on conditions using Vue.js

I am currently working on a project using Vuejs and Nuxt, and I want to incorporate a video into a carousel component alongside jpeg and png images. The carousel component code snippet below demonstrates the setup:

    <template>
    <section>
    <v-card
        class="mx-auto"
        color="#26c6da"
        dark
        max-width="1200"
    >

    <v-carousel>
        <v-carousel-item v-for="(item,i) in items" :key="i" :src="item.src"></v-carousel-item>
    </v-carousel>

    </v-card>

    </section>

    <script>

    export default {
      data() {
        return {
          items: [  {
    id: '1',
    content: '<iframe width="560" height="315" ' +
      'src="https://www.youtube.com/embed/zjcVPZCG4sM" ' +
      'frameborder="0" allow="autoplay; encrypted-media" ' +
      'allowfullscreen></iframe>'
     },
            {
              src: "https://cdn.vuetifyjs.com/images/carousel/sky.jpg"
            },
            {
              src: "https://cdn.vuetifyjs.com/images/carousel/bird.jpg"
            },
            {
              src: "https://cdn.vuetifyjs.com/images/carousel/planet.jpg"
            }
          ]
        };
      }
};

    </script>

    </template>

For more information, refer to this Stack Overflow answer on Displaying video in Nuxt carousel component and this CodePen example: https://codepen.io/anon/pen/MqBEqb

To display a video, you need:

<v-carousel-item v-for="item in items" :key="item.id" v-html="item.content">

And for an image (jpg), use:

<v-carousel-item v-for="(item,i) in items" :key="i" :src="item.src"></v-carousel-item>

How can I dynamically decide between displaying a video or an image based on the object within the exported data array?

Answer №1

A common approach is using v-for in the template and then incorporating v-if to manage the conditional rendering, showcasing one or the other options accordingly.

For more information on using v-for with templates, you can visit:

https://vuejs.org/v2/guide/list.html#v-for-on-a-lt-template-gt

If you want to see a practical example of this concept in action, check out this CodePen link:

https://codepen.io/autumnwoodberry/pen/qXGjXY?editors=1010

Answer №2

If you're looking for a way to address your specific needs, here's a helpful tip. You can utilize both v-if and v-for in combination. By setting conditions based on whether it's related to content or src, you can achieve your desired outcome. Additionally, each data item now includes an id attribute. Want to see the implementation in action? Check out this CodePen link: https://codepen.io/arunredhu/pen/MdebLV

<v-carousel>
    <template v-for="item in items" :key="item.id">
        <v-carousel-item >
            <img v-if="item.src" :src="item.src"/>
            <div class="video-elem" v-if="item.content" v-html="item.content"></div>
        </v-carousel-item>
     </template>
</v-carousel>

Answer №3

One way to utilize a template is by using v-if='item.src'

<div id="app">
  <v-app>
    <v-content>
      <v-container>
        <v-carousel>
          <template v-for="item in items" :key="item.id">
            <v-carousel-item v-if="item.src" :src="item.src"></v-carousel-item>
            <v-carousel-item v-else v-html="item.content"></v-carousel-item>
          </template>
        </v-carousel>
      </v-container>
    </v-content>
  </v-app>
</div>

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

What is the best way to display the key within an object in a mui-datatable?

I attempted to define it in the following manner: { name: "colorList", label: "Color", options: { filter: true, sort: true, customBodyRender: (value, tableMeta, updateValue) => { ...

Searching for an array of objects containing nested arrays in JavaScript

I've been struggling with this function for two days and still can't get it right. I need the function to only return objects that meet all filter criteria in the array. The issue is that it should only return objects that satisfy every filter. ...

How to prevent selecting a particular date in React-datepicker?

Hey there, I'm new to Stack Overflow and I'm facing a challenge that I hope someone can help me with. I'm currently working on a project where the previous developers used a React datepicker. The project managers want to keep it, but I need ...

What are the steps to make React JSX direct to "/profile" and display the profile page?

Throughout my application, I have integrated reach router to facilitate navigation between the different pages. However, I came across a navbar component that I really like and decided to add it to my app. Strangely, clicking on the "to: "/profi ...

Having trouble sending a GET request from the client to my backend route using axios in a React-Node.js/Express setup. Where did I go wrong?

Struggling with making an API request from my backend route (using nodes/express). I'm making an axios request from the client site using React. The express backend route works fine, so the issue must be in my client-side code. I've been stuck on ...

The attribute 'selectionStart' is not a valid property for the type 'EventTarget'

I'm currently utilizing the selectionStart and selectionEnd properties to determine the beginning and ending points of a text selection. Check out the code here: https://codesandbox.io/s/busy-gareth-mr04o Nevertheless, I am facing difficulties in id ...

Issues with Mega Menu functionality preventing items from being clickable and links from properly navigating

Recently, I encountered a strange issue related to the integration of a mega menu found at . Unfortunately, despite integrating the mega menu, the Category and sub category links seem unresponsive - they are not directing me to the desired links. I suspec ...

Why is it necessary for me to utilize JSONP?

What is the significance of using JSONP? A few days ago, I inquired about not receiving a response from a rest server while using jQuery. It turns out that I need to utilize JSONP. I tested this on my own server and it was successful. Now, I am tasked wi ...

"Explore a different approach to file uploading with React Native JavaScript by using either blob or base64 encoding

I am in the process of uploading visuals. When I employ this technique, it functions as expected: formData.append("file",{uri,type,name}); Yet, I prefer not to transmit my visual using the URI. My intention is to divide the visual into distinct sections ...

Issues with retrieving the scope attribute within a directive

I am currently facing an issue where I am unable to access the values stored in $scope.photoRes within my directive. When I use console.log(scope.photoRes) in the directive, it only displays an empty object. Here is the output from the console: Object {fi ...

the webpage is not displaying the style sheet properly

I have set up a local instance of nodejs and am currently running a web service that references a local index.html file upon startup. This web service is operating on my desktop. After experimenting with CSS, I've encountered an issue where the style ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...

Guidelines for creating a dynamic Bootstrap 4 accordion with Jquery

I need help adding a new Bootstrap 4 accordion when a button is clicked. Can someone assist me with implementing this feature in jQuery? I'm not sure if it's possible to add accordions dynamically using jQuery. <script> $(document).re ...

Using VueJS to Create a Range of Years from 1900 to Present Year

I'm currently developing a registration form using VueJS, wherein users need to input their date of birth. My challenge is in generating a list of years starting from 1900 up to the current year within a <select> element. Any suggestions on how ...

execute a rigorous compilation during the ng build angular process

I am currently working on a project using angular-cli and I have configured my package.json with the following scripts: "scripts": { "ng": "ng", "build": "ng build --base-href /test/", "prod": "ng build --prod --base-href /test/" } According to the ...

Loading scripts dynamically with async/await in JavaScript

I may be committing a typical beginner error. Aim I have a script named loader.js, where I intend to provide a collection of JavaScript files that control the shape, size, and position of components. The structure of the file is as follows: const loadSc ...

What is the best way to display form input fields depending on the selected value?

I've been struggling with a seemingly simple issue that I can't seem to find the right solution for, even after scouring Google. I have a form field for input and a select field with various values, including an "Other" option. Here's what ...

Disable sessionStorage property when closing tabs on all pages

I am brand new to the world of .NET development, currently immersing myself in an ASP application with web forms. One particular page in the application contains a table. When a user clicks on a row within this table, it triggers the opening of a new tab. ...

Vue Component, switching state

Feeling like I'm losing it, this should be really simple but it's not working... The idea is that when the link is clicked, the display property toggles between true and false. However, it's not working as expected. Vue.component('d ...

Update the picture dynamically when hovering

Is there a way to change an image randomly when hovering over it? The hover effect is working fine, but the image does not revert back when the mouse moves out. Any suggestions on how to fix this? var arr = ["020", "053", "306", "035", "930"]; function ...