Instead of using a v-if condition, add a condition directly in the Vue attribute

Apologies for the unclear title, as I am unsure of what to name it with regards to my current issue,

I am attempting to create a component layout using vuetify grid. I have a clear idea of how to do this conventionally, like so:

<template>
 <v-flex v-if="totalMenuShowed === 4" xs12 md6 xl6>
  <div>
   // some component
  </div>
 </v-flex>

 <v-flex v-else-if="totalMenuShowed === 3" xs12 md6 xl4>
  <div>
   // some component
  </div>
 </v-flex>

 <v-flex v-else xs12 md12 xl12>
  <div>
   // some component
  </div>
 </v-flex>
</template>

<script>
  props: {
    totalMenuShowed: {
      type: Number,
      default: 4,
    },
  },
</script>

However, my question is

"Is it possible to set conditions based on values or props without using v-if and directly adjusting xs12, md6, xl4 according to the value received?"

For instance, can I do something like the following, where I can modify the inner component's class as needed using @media screen, but cannot change the grid since it is used for other components below and I would prefer not to manually adjust the grid values:

<template>
 <v-flex {totalMenuShowed === 4 ? xs12 md6 xl6 : totalMenuShowed === 3 ? xs12 md6 xl4 : xs12 md12 xl12}>
  <div>
   // some component
  </div>
 </v-flex>
</template>

Could someone assist me with this? I am curious to know if achieving this in Vue is indeed feasible.

Answer №1

To optimize the code, I would incorporate the v-bind feature and utilize a computed method in this way:

<template>
  <v-flex v-bind="vFlexProps">
    <div></div>
  </v-flex>
</template>

<script>
export default {
  props: {
    totalMenuShowed: {
      type: Number,
      default: 4,
    },
  },
  computed: {
    vFlexProps() {
      return {
        xs12: true,
        md6: this.totalMenuShowed < 3 || this.totalMenuShowed > 4,
        ...
      };
    },
  },
};
</script>

Answer №2

v-bind

If you want to make the attributes dynamic, you can use v-bind: or simply :.

  • True-ish values will add the attribute.
  • False-ish values will remove the attribute.
  • Strings/numbers will display as their attribute value.
<v-flex xs12 :md6="totalMenuShowed>=3 && totalMenuShowed<=4" :md12="totalMenuShowed<3 || totalMenuShowed>4"
  :xl6="totalMenuShowed===4" :xl4="totalMenuShowed===3" :xl12="totalMenuShowed<3 || totalMenuShowed>4">
  <div>
   // some component
  </div>
 </v-flex>

To keep it more organized, you can create computed values for these conditions as well.

v-bind details can be found at: https://vuejs.org/api/built-in-directives.html#v-bind

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

Is there a way to adjust the image dimensions when clicked and then revert it to its original size using JavaScript?

Is there a way to make an image in an HTML file change size by 50% and then toggle back to its normal size on a second click using JavaScript? I've attempted to do it similar to the onmouseover function, but it doesn't seem to be working. Any sug ...

An issue is preventing the Angular 2+ http service from making the requested call to the server

I am looking to create a model class that can access services in Angular. Let's say I have the following endpoints: /book/:id /book/:id/author I want to use a service called BooksService to retrieve a list of Book instances. These instances should ...

Tips for maintaining the currentPage variable in Vue when navigating through detail links

As I delve into vue.js, the code snippet below seems to be working smoothly. The concept is quite simple - when a user clicks on the detail, they are directed to another component to view more information about the user. However, what I am struggling with ...

The instance is referencing "greet" during render, but it is not defined as a property or method

At the same time, I encountered another error stating "Invalid handler for event 'click'". <template> <div id="example-2"> <!-- `greet` is the name of a method defined below --> <button v-on:cli ...

Fade in elements individually with the jQuery Waypoints plugin

I am currently using the waypoints jQuery plugin and it is functioning perfectly when fading in on scroll. However, I am facing an issue with making the blocks fade in individually one after the other. Here is the snippet of my jQuery code: $('.hbloc ...

Tips for patiently waiting for a function that is filled with promises

Consider the following function: const getData = () => { foo() .then(result => { return result; }) .catch(error => { return error; }); }; Even though getData does not directly return a promise, it internally handles asynchro ...

Forgetting your password with React JS

On my login page, there is a button labeled "Forget my password". When I click on this button, I want to be taken directly to the correct page for resetting my password. Currently, when I click on "forget my password", it displays beneath the login sectio ...

Encountering difficulties triggering the click event in a JavaScript file

Here is the example of HTML code: <input type="button" id="abc" name="TechSupport_PartsOrder" value="Open Editor" /> This is the jQuery Code: $('#abc').click(function () { alert('x'); }); But when I move this jQuery code to a ...

Is there a way to determine the distance in miles and feet between various sets of latitude and longitude coordinates?

I am working with an array of latitude and longitude coordinates and I am looking to use JavaScript or Typescript to calculate the distance in miles and feet between these points. const latsLngs = [ { lat: 40.78340415946297, lng: -73.971427388 ...

Effortlessly deleting a row with JQuery and PHP without reloading the page

I am currently working on creating a jQuery function to delete a div, but I'm facing an issue. Whenever I click the submit button, the div is not being removed and the page gets refreshed. How can I achieve this without refreshing the page? You can ...

When utilizing the dojox.grid.enhanceGrid function to delete a row, the deletion will be reflected on the server side but

I have a grid called unitsGrid that is functioning correctly. I am able to add and delete rows, but the issue arises when I try to delete rows - they do not disappear from my unitsGrid. I have spent hours trying to debug the code but I cannot seem to fin ...

Electron JS-powered app launcher for seamless application launching

Currently, I am working on a project to develop an application launcher using HTML, CSS, and JS with Electron JS. Each application is linked through an a href tag that directs users to the respective application path. If a normal link is used in the a hr ...

Using a dynamic HTML interface, select from a vast array of over 50,000 values by leveraging the power

I am working on a project that includes a multiselect option with over 50,000 records. We are using AJAX to fetch data from the server based on user searches, which works fine. However, when a user tries to select all records by clicking the "check all" ...

Why is this loop in jQuery executing twice?

$(document).bind("ready", function(){ // Looping through each "construct" tag $('construct').each( alert('running'); function () { // Extracting data var jC2_events = $(this).html().spl ...

Retrieve solely the text content from a JavaScript object

Is there a way to extract only the values associated with each key in the following object? const params = [{"title":"How to code","author":"samuel","category":"categoery","body":"this is the body"}] I'm struggling to figure out how to achieve this. ...

Error message in Node v12: "The defined module is not properly exported."

When trying to export a function in my index.js file, I encountered an error while running node index.js: module.exports = { ^ ReferenceError: module is not defined Is there a different method for exporting in Node version 12? ...

What is the best way to utilize Object.keys for formatting incoming data?

Here is the data I have: const langs = { en: ['One', 'description'], pl: ['Jeden', 'opis'], }; I want to convert it into this format: const formattedData = { name: { en: "One", ...

Tips for resolving an issue with an array and the find method?

Seeking guidance on using the find method. Specifically, I am tasked with searching an array to find a specific string match. The catch is that this string may be nested within one of the objects in its child array. I attempted to create an if statement in ...

I am looking to include query string variables within JSON key-value pairs

On my webpage, I have a .asp page using the following url: page.asp?id=33&album=ourcookout The page.asp file then calls a file.js script. Within the file.js script, there is a line located under a function that reads as follows: url: "post_file.php", M ...

Which is better: Utilizing Ajax page echo or background Ajax/direct HTML manipulation?

I am facing a dilemma and I could really use some guidance. Currently, I am in the process of developing an ordering system using PHP/Smarty/HTML/jQuery. The main functionality revolves around allowing sellers to confirm orders on the site. My goal is to ...