Is there a way to create optional sections within a reusable component's template in a Vue 3 application?

Recently, I've been immersed in developing a Single Page Application (SPA) using the powerful combination of Vue 3, TypeScript, and integrating The Movie Database (TMDB) API.

One interesting challenge I encountered was with my versatile movie card component (MovieCard.vue) that needed to adapt its behavior based on different contexts.

<template>
  <div class="movie card" @click="showDetails(movie.id)">
    <div class="thumbnail">
      <img
        :src="movieCardImage"
        :alt="movie.title"
        class="img-fluid"
      />
    </div>

    <div class="card-content">
      <h2 class="card-title">{{ movie.title }}</h2>
      <p class="card-desc">{{ movie.overview }}</p>
      <span :title="`Score: ${movie.vote_average}`" class="score">{{ movie.vote_average}}</span>
    </div>

    <div class="card-footer">
      <p class="m-0 release">
        Release date: {{ dateTime(movie.release_date) }}
      </p>
      <p v-if="movieGenres" class="m-0 pt-1">
        <span class="genre" v-for="genre in movieGenres" :key="genre.id">
          {{ genre.name }}
        </span>
      </p>
    </div>
  </div>
</template>

... additional script and template code ...

In one context, the MoviesList.vue component is where this movie card shines:

<template>
  <div class="row list">
    <div
      v-for="movie in movies"
      :key="movie.id"
      class="col-xs-12 col-sm-6 col-lg-4 col-xl-3"
    >
      <MovieCard :movie="movie" :genres="genres" />
    </div>
  </div>
</template>

... additional script and template code ...

Here's how it looks:

https://i.sstatic.net/2vIjZ.jpg

In another scenario, specifically within the ActorDetails.vue component, I noticed the need for some tweaks. In this case, I wanted to exclude the votes average display:

<div v-if="knownFor" class="movies">
    <h2 class="section-title">Known For</h2>
    <div class="row list">
        <div
            v-for="item in knownFor"
            :key="item.id"
            class="col-xs-12 col-sm-6 col-lg-4 col-xl-3"
        >
            <MovieCard :movie="item" />
        </div>
    </div>
</div>

Desired result for ActorDetails:

https://i.sstatic.net/TQleZ.jpg

How to make the movie card component elements optional?

I attempted a straightforward approach by styling it out in the ActorDetails component, but ran into issues due to scoped styles:

.score {
    display: none !important;
}

Seeking an effective method to achieve this customization without compromising scoped styling!

Experience it live on Stackblitz

Take a look at the functional implementation on Stackblitz HERE.

Answer №1

To add a rating to the movieCard component, you can include an additional prop as a Boolean. Depending on whether you want the card to display a rating or not, you can pass true/false for this prop.

<span v-if="showRating" :title="`Score: ${movie.vote_average}`" class="score d-flex">{{movie.vote_average}}</span>

When defining props:

showRating: {
   type: Boolean,
   default: false,
},

In the MoviesList component:

<MovieCard :showRating="true" :movie="movie" :genres="genres" />

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

Encountering an npm issue while attempting to execute the command "npx create-expo-app expoApp"

I've been attempting to set up an expo project, but npm is failing to do so. It does create necessary base files like APP.js, but nothing else. Here's the error I encountered: npm ERR! code ENOENT npm ERR! syscall lstat npm ERR! path C:\User ...

PHP Ajax not updating variable as expected

Apologies for the repetitive questions, but I have tried numerous solutions and cannot seem to figure out why this particular one is not working. I am invoking ajax through a click function, but I am unable to retrieve the jList value and update the variab ...

Switching an array with a single string in MongoDB

I'm facing an issue with grouping data in mongoDB and wondering if there's a way to transform an array into a string. The objects included in $lookup are currently displayed in an array format, but I need them in a single string. Here is my code ...

Retrieving the response data from a jQuery AJAX call prior to executing the success function

I have a system that relies on AJAX calls through jQuery for data retrieval. My goal is to capture all the received data along with the request details, without altering the existing $.ajax implementations, and forward it to another API for further analysi ...

Looking for a way to display a personalized 404 error page instead of the default Nginx

My single page application is built with Vue.js. To handle 404 errors at the client side, I have set up my router like this: //at the end of router { path: '/404', name: 'not-found', component: () => import(...) }, { path: ...

How to switch the code from using $.ajax() to employing $.getJSON in your script

How can I convert this code from using AJAX to JSON for better efficiency? AJAX $('#movie-list').on('click', '.see-detail', function() { $.ajax({ url: 'http://omdbapi.com', dataType: 'json', d ...

Is it possible to achieve a file upload in splinter using Python?

A challenging task lies ahead with my web application, where users can upload XML-style files and make modifications directly in the browser. To test this scenario using Splinter, I need to ensure correct input (id="form-widgets-body"): Finding it is eas ...

assigned to a variable and accessed in a different route

Why does the "res.username" variable return as undefined in the second route even though my user needs to login before accessing any route? router.post('/login', passport.authenticate('local'), function(req, res) { res.username = r ...

Parsing PHP array using JavaScript

$namesSelect = "SELECT username FROM users"; $names = mysql_query($namesSelect); $nameCheck = mysql_fetch_array($names) This code snippet retrieves all usernames from the users table and stores them in the $names array. I am now faced with the task of ...

The message "The property 'layout' is not found on the type 'FC<WrapperProps>' in Next.js" is displayed

I encountered an error in my _app.tsx file when attempting to implement multiple layouts. Although the functionality is working as expected, TypeScript is throwing an error Here is the code snippet: import Layout from '@/components/layouts&apo ...

Efficiently filtering and organizing data within a table using Vue js

I've recently set up a table and was looking to implement sorting and searching functionalities using vue.js. While attempting to do so, I came across this helpful resource which provided some guidance, but unfortunately, I still haven't been abl ...

What is causing the extra whitespace on the right side with container-fluid?

Could someone assist me with an issue I'm experiencing when using the container-fluid in Bootstrap? It seems to be leaving some space on the right side of my web page, and as a newcomer to Bootstrap, any help would be greatly appreciated. <link ...

Why is my Vue list not showing the key values from a JavaScript object?

I am struggling to utilize a v-for directive in Vue.js to display the keys of a JavaScript object in a list. Initially, the object is empty but keys and values are populated based on an API call. Here's an example of the data structure (I used JSON.st ...

Modify the event from creating a table on click to loading it on the page onload

Hey there, friends! I've been brainstorming and came up with an idea, but now I'm stuck trying to switch the code to onload(). I've tried numerous approaches, but none seem to be working for me. Below is the code I've been working wit ...

Handling invalid JSON data using JavaScript

Looking to extract data from this URL using Javascript. Here is a sample of the JSON content: {"ss":[["Thu","7:00","Final",,"BAL","19","ATL","20",,,"56808",,"PRE4","2015"],["Thu","7:00","Final",,"NO","10","GB","38",,,"56809",,"PRE4","2015"]]} Most tutori ...

Ways to retrieve the checkbox value using PHP in conjunction with XML

I am currently in the process of learning PHP, XML, AJAX, and other related technologies. I have a form that is working fine for the most part, but I am facing an issue with passing the value/state of a checkbox to my PHP script. It's worth mentionin ...

HTML is not connecting to CSS

I'm having trouble linking my external CSS to my HTML file. In the head of my index.html, I have this code: <head> <title>Twenty by HTML5 UP</title> <meta charset="utf-8" /> <meta name="viewport ...

The mysterious case of the missing CSS file in Node.js

I recently set up a new Node.js Express Project. However, I am facing an issue with the index.ejs file showing the error: Undefined CSS file ('/stylesheets/style.css'). Here is the content of the index.ejs file: <!DOCTYPE html> <html& ...

arrange data within an angular ng-repeat

I'm facing a bit of a challenge with Angular since I'm still new to it. My data looks like this: $scope.datas =[ {name:'haha',datetime:'2015-06-06 09:24:34'}, {name:'taha',datetime:'2015-07-06 19:10:45& ...

How can I restrict the selection of only one checkbox within an iframe window?

Here is my JavaScript snippet: var iframe = document.getElementById('pltc'); iframe.contentWindow.document.open('text/htmlreplace'); iframe.contentWindow.document.write('<input type="checkbox" name="tc0">Yes<input type="c ...