Home » vue » Dynamically set v-for with vue.js

Dynamically set v-for with vue.js

Posted by: admin November 26, 2021 Leave a comment

Questions:

So I’m using Vue.js in my project, and I’ve got a problem: how could I bind filter for v-for dynamically? At some moment of time I’m passing the id of element to the vue method, how could I then put it into v-for item in items | filterBy @{id} in 'id'?

I’ve tried just putting ‘v-for‘ attribute by JQuery ‘attr‘, but this does not seem to work. I suppose that Vue.filter or vm.$set should be used here, but I can’t figure anything out yet.

Would appreciate any possible help!

For example:

var vm = new Vue({
  ...
  methods: {
    bindId: function(id) { //id is passed from html
      var repeat = 'item in items | filterBy "' + id + '" in "id"';
      $(#main).children('.collection').attr('v-for', repeat);
    }
  }
}
Answers:

You can just use a variable in your v-for attribute:

v-for item in items | filterBy id in 'id'

var vm = new Vue({
  ...
  data:function() {
    return {
      id:1
    }
  }
}

Then you could use v-model on an input like text or select, and set the id there:

<input v-model="id"> <!-- Filter to the id inputted here  -->

A few examples here: https://vuejs.org/api/#filterBy