在Vue js中将复选框选择的值分组到数组中
Posted
技术标签:
【中文标题】在Vue js中将复选框选择的值分组到数组中【英文标题】:Grouped Checkbox selected value into array in Vue js 【发布时间】:2020-08-29 02:35:14 【问题描述】:我有一个分组复选框,其数据通过 API 调用填充。我想编写一个 VUE 代码,这样当用户选择一个复选框时,我想将一个对象添加到复选框输入的 v-model 上的数组绑定中。我将按顺序共享填充到复选框中的数据的有效负载以及下面的 VUE 和 html 代码。
"data":[
"customerId":"046094",
"coreSystem":"symplusAM",
"accountId":"MMF046094001",
"fundName":"UNITED CAPITAL MONEY MARKET FUND"
,
"customerId":"046094",
"coreSystem":"symplusAM",
"accountId":"SIS046094001",
"fundName":"UNITED CAPITAL STAFF INVESTMENT SCHEME"
,
"customerId":"046094",
"coreSystem":"symplusAM",
"accountId":"EUROB046094001",
"fundName":"UNITED CAPITAL NIGERIAN EUROBOND FUND "
]
VUE 代码:
<div style="padding-top:40px;" class="col s3">
<div class="input-field">
<h6 class="left-align">Select Portfolio Accounts</h6>
<template v-for="(item, key, index) in portfolioList">
<p>
<label>
<input v-model="selectedPortfolios[item]" :value="item" type="checkbox" class="filled-in" />
<span>
item.fundName
</span>
</label>
</p>
</template>
</div>
</div>
我想要实现的是,只要选择复选框项目,我想为该项目“customerID”:“046094”,“coreSystem”,“symplusam”,“ConsureID”:“MMF046094001”将它作为一个对象添加到绑定到复选框组的数组中,即 selectedPortfolios[item]。请问我如何在Vue中实现这一点。
【问题讨论】:
【参考方案1】:您可以只添加一个指示检查对象的属性,然后您可以使用它来创建计算值。
即使用
<input
v-model="item.$_checked"
type="checkbox"
class="filled-in"
/>
和
computed:
selectedPortfolios()
return this.portfolioList.filter(item => item.$_checked);
,
代码沙盒:https://codesandbox.io/s/tender-haslett-5658h?file=/src/App.vue:278-422
<template>
<div id="app">
<div style="padding-top:40px;" class="col s3">
<div class="input-field">
<h6 class="left-align">Select Portfolio Accounts</h6>
<template v-for="(item, index) in portfolioList">
<p :key="index">
<label>
<input
v-model="item.$_checked"
type="checkbox"
class="filled-in"
/>
<span> item.fundName </span>
</label>
</p>
</template>
</div>
</div>
<div>
<header>Selected</header>
<div v-for="(portfolio, key, index) of selectedPortfolios" :key="index">
portfolio.fundName
</div>
</div>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default
name: "App",
components:
HelloWorld
,
computed:
selectedPortfolios()
return this.portfolioList.filter(item => item.$_checked);
,
data()
return
"portfolioList":[
"customerId":"046094",
"coreSystem":"symplusAM",
"accountId":"MMF046094001",
"fundName":"UNITED CAPITAL MONEY MARKET FUND"
,
"customerId":"046094",
"coreSystem":"symplusAM",
"accountId":"SIS046094001",
"fundName":"UNITED CAPITAL STAFF INVESTMENT SCHEME"
,
"customerId":"046094",
"coreSystem":"symplusAM",
"accountId":"EUROB046094001",
"fundName":"UNITED CAPITAL NIGERIAN EUROBOND FUND "
]
;
</script>
<style>
#app
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
</style>
【讨论】:
以上是关于在Vue js中将复选框选择的值分组到数组中的主要内容,如果未能解决你的问题,请参考以下文章