Vzupo
Vzupo

Reputation: 1468

vuejs auto-filter out an array marked "Bar"

I am new vuejs but learning a lot. I Have an array of items that renders to a list perfectly fine. I do want to not display anything marked Bar? I have tried !Bar but it does not work. Whats the correct way to do this?

var app = new Vue({
  el: "#demo",
  data: {
    items: [{
      childMsg: 'Foo'
    }, {
      childMsg: 'Bar'
    }]
  }
});
<script src="https://unpkg.com/vue"></script>

<div id="demo">
  <ul v-for="item in items">
    <li>{{item.childMsg}}</li>
  </ul>
</div>

Upvotes: 0

Views: 47

Answers (1)

raina77ow
raina77ow

Reputation: 106443

As usual, there are several approaches. One most straightforward is to exclude the item directly within v-for element template, like this:

<li v-if="item.childMsg !== 'Bar'">{{item.childMsg}}</li>

An alternative would be creating a computed property: array of items that do not match the pattern. Then you can rebase your v-for onto that property. Here's how it can be done:

var app = new Vue({
  el: "#demo",
  data: {
    exclude: '',
    items: [{
      childMsg: 'Foo'
    }, {
      childMsg: 'Bar'
    }]
  },
  computed: {
    filteredItems() {
      return this.items.filter(x => x.childMsg !== this.exclude);
    }
  }
});
<script src="https://unpkg.com/vue"></script>

<div id="demo">
  <label>Exclude word... <input type="text" v-model="exclude" /></label>
  <ul v-for="item in filteredItems">
    <li>{{item.childMsg}}</li>
  </ul>
</div>

Upvotes: 3

Related Questions