vue中v-for和v-if一起使用之使用compute


版本

vue 2.9.6
element-ui: 2.15.6

目标效果

说明

在 vue 2.x 中,在一个元素上同时使用 v-if 和 v-for 时,v-for 会优先作用

解决方法

  1. 选择性地渲染列表,例如根据某个特定属性(category )来决定不同展示渲染,使用计算属性computed
  2. 使用template占位,将循环放在template中,v-if作用于元素,此方法script中不用定义computed方法,见 https://www.cnblogs.com/fengzi-2016/p/16242434.html

核心代码片段

# html
...
奥迪

  {{item.name}}

...
# script
...
computed: {
  links0: function() {
    return this.links.filter((item) => {
      return item.category === 0
    })
  },
  links1: function() {
    return this.links.filter((item) => {
      return item.category === 1
    })
  },
  links2: function() {
    return this.links.filter((item) => {
      return item.category === 2
    })
  }
},
...

Car.vue

点击查看代码