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

Having trouble with the `npm start` command while working with react.js?

Currently, I am in the process of setting up React.js. To achieve this, I executed npm install -g create-react-app followed by create-react-app my-app. Afterward, I proceeded to run the npm start command but encountered the error displayed below. https:// ...

The combination of sass-loader and Webpack fails to produce CSS output

Need help with setting up sass-loader to compile SCSS into CSS and include it in an HTML file using express.js, alongside react-hot-loader. Check out my configuration file below: var webpack = require('webpack'); var ExtractTextPlugin = require ...

How can I determine the size of the custom options dropdown in Magento?

I'm facing a challenging issue that I can't seem to crack. It might be because I'm still learning the ropes and struggling with technical jargon. Please bear with me as I try to explain my problem. Here is a summary of what I'm trying ...

Nodemon has encountered an issue: Unable to listen on port 5000. The address is already in use

During the creation of my project with nodejs and express for the backend, everything was running smoothly. However, whenever I made changes to a file, nodemon would encounter an error preventing the server from restarting: Error: listen EADDRINUSE: addre ...

When trying to set up Plaiceholder in a Next.js/Webpack 5 environment, you may encounter the following issue: "Error: Module not found - Can't resolve 'child_process

While working on my Next.js application, I encountered an issue after installing/importing Plaiceholder for generating placeholder images. The error message I received is: Module not found: Can't resolve 'child_process' Node version: 14.18. ...

Converting data into a multidimensional array in AngularJS: A comprehensive guide

Struggling to convert a JSON array into a multidimensional array, looking for some guidance. I attempted using _.groupBy in underscore.js, but it's not proving successful with the nested array. If there is any way to convert from the given data [{ ...

Are your GetJSON requests failing to execute properly?

I have a code snippet that executes in a certain sequence and performs as expected. <script> $.getJSON(url1, function (data1) { $.getJSON(url2, function (data2) { $.getJSON(url3, function (data3) { //manipulate data1, data2, ...

What triggers the invocation of the onerror handler in XMLHttpRequest?

I am facing a bit of confusion when trying to understand the functionality of XMLHttpRequest's handlers. After reading the specification regarding the onerror handler, it mentions: error [Dispatched ... ] When the request has failed. load [Dispa ...

What is the best way to separate one dropdown area from another dropdown area?

I have two dropdown menus where, when an option with the value "other" is clicked, it generates a text area just below the dropdown menu. Both sections are functioning correctly, but I had to create separate parent wrappers for each in order to do so. How ...

Using the Google Chrome console, execute a command on each page within a specified website

While browsing a website, I noticed a bug that required me to manually run a JavaScript function each time I navigated to a different page in order for the site to work smoothly. Is there a way to automate this process upon page load? I am using Google C ...

Obtaining various values for checkboxes using dynamic data in a React application

Retrieve all checkbox values dynamically import * as React from "react"; import Checkbox from "@mui/material/Checkbox"; import FormControlLabel from "@mui/material/FormControlLabel"; import axios from "axios"; expor ...

What could be causing the CORS error I'm encountering with my XmlHttpRequest?

After re-installing Python to resolve some environment issues, I started encountering a CORS error during an XMLHttpRequest: The CORS policy is blocking access to 'localhost:8000/admin/login/?next=/api/report_builder/api/fields' (redirected fro ...

Looping through a series of JavaScript objects in a JSON

I've encountered an issue when trying to run a loop with a JSON query inside it. Here's what my code looks like: for (var i = 0; i < numitems; i++) { var currentitem = items[i]; $.getJSON("http://localhost/items.php", {'itemname&ap ...

Ensuring Angular applications can effectively run on Internet Explorer

In my Angular application, I have implemented the functionality where users can choose a map to select the delivery point for goods. However, there seems to be an issue with this feature in Internet Explorer (IE) - the map opens but the delivery points ar ...

Utilizing AJAX in Datatables- Effortlessly sharing a URL link to a designated page

I've recently encountered an issue while using Datatables and AJAX to retrieve data from my Rails server. The problem arises when I try to share a specific page (let's say page 2) with another user who is also using Datatables. Due to the paginat ...

Simplify an array in Javascript

I have a collection of objects structured in the following way: let list = [ { 'items': [ 'item 1', 'item 2' ] }, { 'items': [ 'item 3' ] } ] My goal is to flatte ...

Error encountered in Angular CLI: Attempting to access property 'value' of an undefined variable

I am encountering an issue while trying to retrieve the values of radio buttons and store them in a MySql database. The error message I receive is TypeError: Cannot read property 'value' of undefined. This project involves the use of Angular and ...

Steps for importing a JavaScript file from Landkit into a Vue project

Currently, I am working on an interesting project and utilizing Vue with Landkit Bootstrap. However, I am encountering issues with the JavaScript behavior of the Landkit component. I usually import the following links in my index.html file, but in the new ...

Saving the output of an AngularJS expression in an input field

Looking at the calculations below, I am currently evaluating an expression, {{ annualIncome * 4.5 }}, in one input and then re-evaluating the same expression in another input. Instead of saving the result and transferring it to the other input, I am repeat ...

Python web scraping: Extracting data from HTML tag names

Seeking help with extracting user data from a website by retrieving User IDs directly from tag names. I am utilizing python selenium and beautiful soup to extract the UID specifically from the div tag. For instance: <"div id="UID_**60CE07D6DF5C02A987E ...