Morgan Le Floc'h
Morgan Le Floc'h

Reputation: 324

Vuejs use function in v-for

Does anyone know if it's possible to use a function in a v-for loop? I would like to do something like:

<div v-for="(stbc, index) in data">
    <select>
        <option v-for="foo in bar(stbc.arg1, stbc.arg2)" :value="foo">
            {{ foo }}
        </option>
    </select>
</div>

[...]
props: {
    Configuration: { required: true }
},
computed: {
    data(){
      return this.Configuration.something
             .filter(stbc => {
               return stbc.val !== "no"
             });
    }
},
methods: {
    bar(arg1, arg2){
        this.$http.get(`server_url/baz?arg1=${arg1}&arg2=${arg2}`)
                  .then(res => { return res.split('\n') });
    }
}

I tried but without success :(

Thank you !

Upvotes: 5

Views: 14899

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74595

v-for can iterate over a the result of any valid expression (though personally I would consider adding a computed property instead).

However, if you're calling the server as you indicate in your comment, you are introducing asynchronous code, and bar(arg1, arg2) is probably returning a promise, rather than an array of strings.

I guess what you want to do is:

props: {
  Configuration: { required: true }
},
data() {
  return {
    serverData: []
  };
},
mounted() {
  this.fetchData();
},
methods: {
  fetchData() {
    // obtain `arg1` and `arg2` from `this.Configuration`
    // (or use a computed property if you prefer)

    if (arg1 && arg2) {
      this.$http.get(`server_url/baz?arg1=${arg1}&arg2=${arg2}`)
                .then(res => { this.serverData = res.split('\n') });
    }
  }
}

Then just refer to serverData in your template. The array will be empty until the promise returned by the AJAX call resolves.

If the Configuration prop changes during the lifetime of the component, you may want to also add a watcher, to call fetchData again with the new values.

Upvotes: 4

Cesar Oliveira
Cesar Oliveira

Reputation: 46

yes, you could use the computed to achieve that instead of methods, see bellow

<select>
    <option v-for="foo in bar(arg1, arg2)" :value="foo">
        {{ foo }}
    </option>
</select>

[...]

computed: {
    bar(arg1, arg2){
        //get data from server
        return serverData; //this is a string array
    }
}

See this fiddle: https://jsfiddle.net/49gptnad/2449/

I hope this will help you.

Upvotes: 3

Related Questions