v-for循环中的动态数组名称

two*_*oam 1 vue.js

是否有可能使v-for数组成为动态?像这样:

<div v-for="(company, index) in arrayName">
    ....
</div>
Run Code Online (Sandbox Code Playgroud)

数据:

data() {
    return {
        companies: [],
        arrayName: 'companies'
    }
},
Run Code Online (Sandbox Code Playgroud)

kai*_*ris 6

它可以通过计算属性来实现

模板:

<div v-for="(company, index) in myArray">
    ....
</div>
Run Code Online (Sandbox Code Playgroud)

例如:

computed: {
  myArray() {
    return this[this.arrayName];
  },
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*ech 5

我最初的反应是质疑你为什么这样做!

如果您确定这是您想要的,您可以使用计算属性:

computed: {
    things() {
        return this.$data[this.arrayName];
    }
}
Run Code Online (Sandbox Code Playgroud)

然后您的模板可以循环播放things

但是,我可能会采用另一种方法。根据评论中的讨论,使用过滤器的方法可能是:

data() {
    companies,
    filterActive: false
},
computed: {
    things() {
        if (this.filterActive) {
            return this.companies.filter(company => company.isActive);
        }

        return this.companies
    }
}
Run Code Online (Sandbox Code Playgroud)

我假设公司数组包含一些您可以用来确定它们是否活跃的数据。

现在你的按钮需要做的就是filterActive在 true 和 false 之间切换。