遍历计算的属性Vue

时间:2019-03-07 05:27:46

标签: javascript vue.js

我有一个包含以下数据的组件,它是一个简单的数组:

data() {
        return {
            permissions: [
           { id: '1' , name: 'create'},
           { id: '2' , name: 'edit'},
           { id: '3' , name: 'delete'}
           ]
        }
    }

此外,我还创建了以下使用此数组的计算属性,并返回对象数组:

computed: {
     getFormPermissionId(){
       var permission = this.permissions
       for(let i = 0;i < permission.length; i++ ) {
         return  permission[i].id
       }
     }
  }

我想要没有v-for的模板中的此输出,如下所示:

1
2
3

我不知道如何在模板中应用。这是我的代码https://codepen.io/thon0209/pen/vPybWw

谢谢:)

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
       for(let i = 0;i < permission.length; i++ ) {
         return  permission[i].id
       }
     }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

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

3 个答案:

答案 0 :(得分:0)

您正在使用.navbar { position: fixed; top: 0; left: 0; right: 0; height: 30px; background: rgba(255, 255, 255, 0.8); } ,它将停止功能的进一步执行。您可以创建一个变量,并在内部循环中将值连接到该变量,最后return将其连接。

return
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;
     }
  }
})

答案 1 :(得分:0)

您可以创建字符串并且可以执行相同的操作

Eval

完整示例

IsTerm/Eval
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;
        }
    }
})

答案 2 :(得分:0)

这是您可以做的:

<div id="app">  
 <div v-for="(item, index) in permissions" :key="index">
    {{item.id}}
    <br/>
  </div>
</div>

您只需删除计算出的值即可。