Is there a way I can incorporate v-for with a computed variable?

I am trying to display navigation items based on my authority and other conditions. Below is the code I am using:

 <template v-for="(subItem, index2) in item.children">
     <v-list-item sub-group  link :to="subItem.link" exact v-if="item.auth === true"  :key="index + '_sub_' + index2">
         <v-list-item-title v-text="subItem.title" ></v-list-item-title>
     </v-list-item>
</template>

I want to disable click when v-if="item.auth === true

Below is my object structure:

children: [
    {name:'menu1', title:'menu1', link:'/company/menu1', auth: () => {return this.currentNav===0 }}, // not working
    {name:'menu2', title:'menu2', link:'/company/menu2', auth: true}, // works
    {name:'menu3', title:'menu3', link:'/company/menu3', auth: this.MyInfo.Auth.menu3Auth === true }, // works, but menu visibility does not change when MyInfo.Auth.menu3Auth value changes.
    {name:'menu4', title:'menu4', link:'/company/menu4', auth: () => {return this.currentNav===4 || this.MyInfo.Auth.menu3Auth === true }}, 
    {name:'menu5', title:'menu5', link:'/company/menu5', auth: () => {return this.MyInfo.Auth.menu5Auth === false && this.MyInfo.Auth.menu3Auth === true  }
}

However, it is not functioning as expected. How can I resolve this issue?

Answer №1

If you need to apply conditions within a v-for loop, it's recommended to move them into a computed property:

computed: {
  authItems() {
    return this.items.children.filter((x) => {
      if (typeof x.auth === 'function') {
        return x.auth();
      }
      return x.auth === true;
    });
  },
},

After defining the computed property, you can use it in your template like this:

 <template v-for="(subItem, index2) in authItems">
     <v-list-item sub-group  link :to="subItem.link" exact :key="index + '_sub_' + index2">
         <v-list-item-title v-text="subItem.title" ></v-list-item-title>
     </v-list-item>
</template>

This approach ensures better readability and maintainability compared to directly filtering items within the v-for loop.

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 the performance impacted by using try / catch instead of the `.catch` observable operator when handling XHR requests?

Recently, I encountered an interesting scenario. While evaluating a new project and reviewing the codebase, I noticed that all HTTP requests within the service files were enclosed in a JavaScript try / catch block instead of utilizing the .catch observable ...

Node.js refuses to launch - the dreaded error 404, signaling that it has mysteriously vanished

I am brand new to node.js, so please be patient with me as I learn. Currently, I am using the express framework and attempting to create a basic application that displays content as HTML. Below is the essentials of my app.js: var express = require(' ...

Timeout for AngularJS Bootstrap UI Modal

I am having some trouble with opening a bootstrap modal using the $timeout function. The issue I am facing is that the modal keeps opening multiple times as the timeout fires repeatedly. Any assistance or suggestions on how to resolve this problem would be ...

How can I effectively monitor and track modifications to a document's properties in MongoDB?

I'm wondering how to effectively track the values of a document in MongoDB. This involves a MongoDB Database with a Node and Express backend. For example, let's say there is a document within the Patients collection: { "_id": "4k2lK49938d ...

The scrollbar will be visible only when the mouse hovers over the table

I have been experimenting with customizing the scrollbar appearance of an ant design table. Currently, the scrollbar always displays as shown in this demo: https://i.stack.imgur.com/vlEPB.png However, I am trying to achieve a scroll behavior where the sc ...

The vanishing act: Semantic UI menu disappears when you click

My objective is to create a persistent left-side menu using Semantic-UI. I want to implement two different states for the menu - one with text for each item and another with an image for each item. However, I am facing some challenges that have me complete ...

Tips for utilizing Vue router query parameters while in hash mode:

Is there a more efficient way to access URL parameters in Vue methodology, without having to rely on window.location.href and parsing the URL? router/index.js const router = new Router({ mode: 'hash', routes: [] }); router.beforeEach((to, f ...

Prevent any screen interactions by disabling clicks, and then re-enable them either after a set amount of

My app uses PhoneGap and jQuery Mobile. The issue I am facing is that when I navigate from page A to page B with a single click, everything works fine. However, if I accidentally double-click on page A and move to the next screen (page B) before it's ...

A helpful guide on resetting ReactJs to its default state when data is not found

Currently, I'm fetching data from my database, but just for the sake of this question, I have opted to manually create an example with fake data. I am in the process of creating a search bar for my users to navigate through all the data retrieved fro ...

Overlap one element entirely with another

Currently, I am working on a way for an element called overlayElement to completely cover another element known as originalElement. The overlayElement is an iFrame, but that detail may not be significant in this scenario. My goal is to ensure that the over ...

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 ...

The React Native Expo is throwing an error stating that it is unable to locate the module 'minizlib'

At the instructions available in the read.me of https://github.com/react-community/create-react-native-app Upon selecting my template using the expo init command, I encountered the following error: Cannot find module 'minizlib' Error: Cannot fi ...

What is the best way to populate MongoDB with information retrieved from an external API?

Recently, I've been diving into the world of NodeJS with mongoose & mLab. As someone new to these technologies, I'm slowly piecing together my model. Here's what it looks like for now, with plans to expand the schema down the road. cons ...

Searching for two distinct nested key values in Ramda

I am new to Ramda and wondering if it is possible to retrieve two different key values at the same level of an object. Below is the code I have added: In this scenario, the object 'list' contains keywords 'users' and 'employee&ap ...

The dimensions of GridStack items specified in pixels for both height and width

I am facing a challenge with my GridStack items, which each contain elements like graphs that need to be re-rendered when the size of the gridstack item (cell) changes. I am attempting to use the change event on GridStack to detect the modified items and t ...

Utilizing JQuery to modify the element's id and trigger a function upon clicking

There is an element with a specific ID that I have changed. However, even after changing the ID and clicking on the element with the new ID, it still triggers the function associated with the old ID. $('#1st').click(function(){ $('#1s ...

What is the reason for triggering a rerender when there is a modification to a map() element using document.querySelector() in JS/next.js?

const slides = [ [string1, string2, stringi], [string1, string2, stringi], [string1, string2, stringi], [string1, string2, stringi], ]; const changeSlide = (num) => { const discipline = document.querySelector("#changeSlide-&quo ...

Utilizing const as the iteration variable in a for loop

I've grasped the concept of using var and let in a for loop in typescript/javascript, but can someone shed light on how and why a const variable as a loop variable behaves? for (const i = 0; i < 5; i++) { setTimeout(function() { console.log( ...

Iterating through a series of Axios requests nested within each other to handle pagination in an

I need help iterating through the API response that includes pagination. Below is a snippet of the API response: { count: 165, next: "http://example.com/name?offset=30&per_page=30", previous: null } Here is my useEffect hook: const [datas, se ...

Using Ng-options in AngularJS to populate a select dropdown with an array of arrays

I'm encountering an issue with displaying options from an array of arrays in a select dropdown. Can someone point out what I might be doing wrong? Check out my code here: https://plnkr.co/edit/HMYbTNzkqkbAGP7PLWWB?p=preview Here's the HTML snipp ...