zoukankan      html  css  js  c++  java
  • 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>
    
  • 相关阅读:
    HTML DOM 12 表格排序
    HTML DOM 10 常用场景
    HTML DOM 10 插入节点
    HTML DOM 09 替换节点
    HTML DOM 08 删除节点
    HTML DOM 07 创建节点
    022 注释
    024 数字类型
    005 基于面向对象设计一个简单的游戏
    021 花式赋值
  • 原文地址:https://www.cnblogs.com/axingya/p/14280436.html
Copyright © 2011-2022 走看看