Vue - 在这种情况下如何传递数组?
Posted
技术标签:
【中文标题】Vue - 在这种情况下如何传递数组?【英文标题】:Vue - how to pass array in this case? 【发布时间】:2021-01-21 02:32:28 【问题描述】:这是我的示例代码。我想创建一个小型表单生成器。
我将有许多选择字段。如何将数组传递到循环中?我的代码不起作用,但我希望你知道我想要得到什么效果。
<template>
<div>
<div v-for="(input, index) in formBuilder" :key="index">
<h1> input.name </h1>
<div>
Options:<br />
formBuilder.options
</div>
</div>
</div>
</template>
<script>
import mapState from "vuex";
export default
data()
return
formBuilder: [
name: "Name",
options: this.versions,
,
name: "Host",
options: this.countryList,
,
],
;
,
computed: mapState(["versions", "countryList"]),
;
</script>
编辑。 下面,我添加了一个有效的版本。但它可以以更好的方式完成吗?这是正确的方法吗?
有效:
<template>
<div>
<div v-for="(input, index) in formBuilder" :key="index">
<h1> input.name </h1>
<div>
Options:<br />
input.options
</div>
</div>
</div>
</template>
<script>
import mapState from "vuex";
export default
data()
return
formBuilder: [
name: "Name",
options: [],
,
name: "Host",
options: [],
,
],
;
,
created()
this.formBuilder[0].options = this.versions;
this.formBuilder[1].options = this.countryList;
,
computed: mapState(["versions", "countryList"]),
;
</script>
【问题讨论】:
使用input.options
代替formBuilder.options
: vuejs.org/v2/guide/list.html
这能回答你的问题吗? Use computed property in data in Vuejs
这是我的错误。我已经更正了。我更新了帖子。这种方法对我有用。但是没有更好的解决方案吗?最重要的是:这是正确的解决方案吗?
【参考方案1】:
正如https://***.com/users/381282/michal-lev%c3%bd 提到的那样。计算属性是您的“正确解决方案”。
computed:
...mapState(['versions', 'countryList']),
formBuilder()
return [
name: "Name", options: this.versions ,
name: "Host", options: this.countryList ,
]
说明:
如果您将代码放在created
中,它只会在组件创建时准备一次formBuilder
。
如果您使用computed
,则每次this.versions
或this.coutryList
更新时都会重新计算formBuilder
。
【讨论】:
非常感谢。这就是我需要的!以上是关于Vue - 在这种情况下如何传递数组?的主要内容,如果未能解决你的问题,请参考以下文章
Vue:axios中POST请求传参问题---传递数组 (补充)