Vuejs 在 v-for 中使用函数

Mor*_*c'h 5 javascript vue.js

有谁知道是否可以在 v-for 循环中使用函数?我想做类似的事情:

<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') });
    }
}
Run Code Online (Sandbox Code Playgroud)

我试过了,但没有成功:(

谢谢 !

Tom*_*ech 4

v-for可以迭代任何有效表达式的结果(尽管我个人会考虑添加一个computed属性)。

但是,如果您按照注释中的指示调用服务器,那么您将引入异步代码,并且bar(arg1, arg2)可能返回一个承诺,而不是一个字符串数组。

我想你想做的是:

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') });
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

serverData然后只需在您的模板中引用即可。在 AJAX 调用返回的 Promise 解析之前,该数组将为空。

如果Configurationprop 在组件的生命周期内发生变化,您可能还需要添加一个观察者,以fetchData使用新值再次调用。