• Vue中v-if和v-for同时使用的处理方法


    当v-if和v-for同时使用时,因为v-for的优先级会更高,所以在使用时会报错,目前常用的处理方法有两种
    1、template

    <template v-for="(item, index) in list" :key="index">	
       <div v-if="item.isShow">{{item.title}}</div>
    </template>
    

    2、计算属性(推荐)

    <template>
     <div>
    	<el-table-column
                v-for="(e, i) in columns1"
                :key="i"
                :prop="e.code"
                :label="e.name"
                sortable
                width="150"
              >
                <template slot-scope="scope">
                <span>{{ scope.row[e.code]}}</span>
                </template>
              </el-table-column>
    </div>
    </template>
    <script>
    export default {
      name:'A',
      data () {
        return {
        };
      },
      computed: {//通过计算属性过滤掉列表中不需要显示的项目
        columns1: function () {
          return this.columns.filter(function (e) {  // columns是后端返回的数组,对改数组做筛选返回新数组,在上面进行遍历
            switch (e.is_view_able){   // columns遍历出的数据e中的参数符合什么就返回对应的参数
            case "true": 
                  return 1
                  break;
            case "false": 
                  return 0
                  break;
            default:return Boolean(val);
          }
          })
        }
    };
    </script>
    

    简单点来写的话就是

    <template>
     <div>
    	<div v-for="(user,index) in activeUsers" :key="user.index" >
    		{{ user.name }} 
    	</div>
    </div>
    </template>
    <script>
    export default {
      name:'A',
      data () {
        return {
          users: [{name: 'aaa',isShow: true}, 
                  {name: 'bbb',isShow: false}]
        };
      },
      computed: {//通过计算属性过滤掉列表中不需要显示的项目
    	activeUsers: function () {
    	  return this.users.filter(function (user) {
    		return user.isShow;//返回isShow=true的项,添加到activeUsers数组
    	  })
    	}
      }
    };
    </script>
    
  • 相关阅读:
    同名的const 成员函数
    模板元编程中的“hello world”
    枚举联合不能用作基类,也不能有基类
    不能重载的操作符
    不同级别成员对应三种继承的结果:
    c++ error: creating array of references( declaration of 'a' as array)
    leetcode 剑指offer 03 数组中重复的数字
    Lintcode 89 K sum
    leetcode 322. Coin Change
    Leetcode 416. Partition Equal Subset Sum
  • 原文地址:https://www.cnblogs.com/axingya/p/14280436.html
Copyright © 2020-2023  润新知