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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM