Traverse a computed attribute in Vue.js

I am working with a component that contains a simple array as its data:

data() {
        return {
            roles: [
           { id: '1' , name: 'admin'},
           { id: '2' , name: 'user'},
           { id: '3' , name: 'guest'}
           ]
        }
    }

In addition, I have implemented a computed property that interacts with this array and outputs a new array of objects:

computed: {
     getRoleId(){
       var roleList = this.roles;
       let ids = [];
       for(let i = 0; i < roleList.length; i++ ) {
         ids.push(roleList[i].id);
       }
       return ids;
     }
  }

I want to display this output in the template without using v-for, like this:

1
2
3

I am unsure how to achieve this in the template. Here is my code snippet on CodePen here.

Thank you :)

var app = new Vue({
  el: '#app',
  data() {
    return{
      roles: [
        {
          id:1,
          name:'admin'
        },
        {
          id:2,
          name:'user'
        },
        {
          id:3,
          name:'guest'
        }
     ]
    }
  },
  computed: {
     getRoleId(){
       var roleList = this.roles;
       let ids = [];
       for(let i = 0; i < roleList.length; i++ ) {
         ids.push(roleList[i].id);
       }
       return ids;
     }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">  
  {{getRoleId}}
</div>

Answer №1

It is recommended to utilize a variable within a loop and concatenate values to it instead of using return which stops further function execution.

var app = new Vue({el: '#app',data() {return
{permissions: [
        {id:1,name:'create'},
        {id:2,name:'edit'},
        {id:3,name:'delete'}]
    }
  },
  computed: {
     getFormPermissionId(){
       var permission = this.permissions
       let result = '';
       for(let i = 0;i < permission.length; i++ ) {
         result += permission[i] + '<br>'
       }
       return result;
     }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">  
  {{getFormPermissionId}}
</div>

Answer №2

To generate a string and perform the same action

var app = new Vue({
    el: '#app',
    data() {
        return {
            permissions: [{
                    id: 1,
                    name: 'create'
                },
                {
                    id: 2,
                    name: 'edit'
                },
                {
                    id: 3,
                    name: 'delete'
                }
            ]
        }
    },
    computed: {
        getFormPermissionId() {
            var permission = this.permissions;
            //Generating String 
            str = "";
            for (let i = 0; i < permission.length; i++) {
                 str += permission[i].id + "\n";
            }
            return str;
        }
    }
})

Example in detail

    var app = new Vue({
        el: '#app',
        data() {
            return {
                permissions: [{
                        id: 1,
                        name: 'create'
                    },
                    {
                        id: 2,
                        name: 'edit'
                    },
                    {
                        id: 3,
                        name: 'delete'
                    }
                ]
            }
        },
        computed: {
            getFormPermissionId() {
                var permission = this.permissions;
                //Creating String 
                str = "";
                for (let i = 0; i < permission.length; i++) {
                    str += permission[i].id + "\n";
                }
                return str;
            }
        }
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">  
  {{getFormPermissionId}}
</div>

Answer №3

Consider the following options:

<div id="container">
 <div v-for="(element, number) in items" :key="number">
    {{element.label}}
    <br/>
  </div>
</div>

You may also choose to eliminate the computed property.

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 limit a form to only allow 2 checkbox selections?

Seeking advice on implementing a form for a website giveaway featuring 3 prizes. Each participant should only be able to select 2 items from the list. I've already created a JavaScript-based form, but I'm concerned about its reliability since it ...

Identifying functions that contain dots in their names using JSHint

While running jshint on a JavaScript file, I encountered functions with dots in their names for namespacing purposes. Specifically, within the d3 library, there is a significant portion of code that resembles: d3.select("something") Should I simply disab ...

Leveraging jQuery in Content Scripts for Chrome Extensions

I am currently working on developing a Chrome extension that will prompt a small input whenever a user highlights text on a webpage (similar to Medium's feature that allows you to tweet highlighted text). While I am making progress, I believe using j ...

Different ways to provide user feedback on a SPA website following AJAX requests

I have a single-page application website developed using React.js. What are some options for notifying the user of successful/failed/pending AJAX calls resulting from various user interactions? I am aware of Toastr-style messages that appear in the corner ...

Issue with inserting data into MySQL database using Node.js (JavaScript)

I am attempting to utilize the insert function but keep encountering an error. I want to add a user's name to the user table. The function I am using is: function insert(tableName, toField, value){ connection.connect(); var queryString = "i ...

Avoid invoking the throttle function from lodash

I am currently facing an issue in my React project with a throttle function from lodash. The requirement is that the function should not be executed if the length of the parameter value is zero. I have tried checking the length of the value and using thro ...

Sharing Iframes across various Components within a Single Page Application (like Youtube)

Did you know that Youtube now lets you minimize the player while browsing the site? It's similar to the functionality on LolEsports.com with Twitch and embedded Youtube players. I'm interested in adding this feature to my own website. Here' ...

How to Ensure Screen Opens in Landscape Mode with Phaser3

https://i.stack.imgur.com/keCil.pngIn my Phaser3 game, I am trying to achieve the functionality where the game opens horizontally in a webview without requiring the user to rotate their phone. The vertical photo below shows the game in its current state. W ...

Retrieve a specific object from a JSON array nested within an array of objects, by utilizing a PHP script

There are two JSON files that contain JSON objects, with one of the files containing an array of objects within another array of objects. The first file is orders.json: { "orders": [ { "address": null, ...

Directive in Angular for customer management with filtering and sorting functionality

I am struggling to organize the JSON object by userType using ng-repeat. While I have successfully retrieved and displayed the data, my ISSUE is that I need to sort and display two different tables for the following list: One for MARRIED individuals and an ...

tool for showcasing data on a webpage with a specific layout

Which chart library is best suited for presenting data in the formats shown in the images below? Can HighCharts handle these formats? Does Google Charts allow for a combination of bubbles and lines? ...

Execute AngularJS $q.all, regardless of any errors that may occur

Is there a way to ensure $q.all is triggered even if the promises return errors? I'm working on a project where I need to make multiple $http.post requests, sending user-inputted values from text fields. The backend (Django REST framework) has a valu ...

Why isn't Gzip compression working in webpack? What am I missing?

After comparing the compression results of manual webpack configuration and create-react-app for the same application, it became clear that create-react-app utilizes gzip compression, resulting in a significantly smaller final bundle size compared to manua ...

Received undefined response from Axios.get() request

While working with the code below, I encountered an issue. The axios get request from await axios.get('/products/api') is functioning properly and I can see the data in the console. However, for await axios.get('/users/api'), 'Unde ...

Uploading a file to NodeJS via POST and seamlessly forwarding it to another API without storing it on disk

In order to transfer a file from a user through a React UI (with axios), then send it to a NodeJS method via POST using Express, and finally forward the same file directly to another API (.NET WebAPI) without saving it to disk, I am faced with an issue whe ...

Utilize JSON data loading instead of directly embedding it onto the page for improved website

I've integrated Mention.js into my website, allowing a dropdown list of usernames to appear when "@" is typed in a designated textarea. <textarea id="full"></textarea> While it's functioning well, the examples provided only show how ...

Can a client receive a response from server actions in Next.js 13?

I'm currently developing a Next.js application and I've created an action in app/actions/create-foo-action.js. In this server action, I am attempting to send a response back to the client. import { connectDB } from "@utils/database" imp ...

jquery makes it easy to create interactive hide and show effects

The main concept is to display the element upon clicking and hide it when there is any mouse click event. Below is the HTML code I'm using: <ul> <li> <span class="name">Author 1</span> <span class="affiliation"&g ...

Managing browser back button functionality

I've been struggling to find a solution for handling the browser back button event. I would like to prompt the user with a "confirm box" if they click on the browser back button. If they choose 'ok', I need to allow the back button action, ...

How can you utilize jQuery to export multiple-page HTML content into a PDF document?

I'm having trouble exporting HTML to PDF using jQuery, especially when the HTML content spans multiple pages in the PDF file. Below is my current code snippet: $("body").on("click", "#downloadPDF", function () { html2canvas($('#dow ...