Vue element复选框

文章描述:

Vue element框架复选框获取选中的值

<template>
	<div>
		<div v-for="(item,index) in list" :key="index">
            
            <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange(item)">
                <el-checkbox :label="item.name">{{item.name}}</el-checkbox>
            </el-checkbox-group>
            
        </div>
	</div>
</template>

<script>

export default {
	components:{
		
	},
	beforeMount(){
        console.log('挂载前',this.list);
    },
	data(){
		return{
			list:[
				{
				    id:1,
				    name:'北京'
				},
				{
				    id:2,
				    name:'上海'
				},
				{
				    id:3,
				    name:'广州'
				}
			],
			arr:[],				// 选中id数组
			checkedCities:[],	// 选中名称数组
		}
	},
	created() {
		
	},
	methods:{
		handleCheckedCitiesChange(value){
			
			// 选中的城市name
			// console.log(value.name)
			
			console.log(value.id)
			// 把城市id存入arr
			if(this.arr.indexOf(value.id) === -1){
			    this.arr.push(value.id)
			}else{
			    this.arr.splice(this.arr.indexOf(value.id),1)
			}
			console.log(this.arr)
			console.log('打印数组',this.checkedCities);
		}
	}
}
</script>

<style>

</style>

[1, 3]

[‘北京’, ‘广州’]

 

第二种

<template>
  <el-checkbox-group v-model="checked" @change="test">
      <el-checkbox v-for="item in checkList"
           :key="item.id"
           :label="item.id"
          >{{item.label}}
      </el-checkbox>
  </el-checkbox-group>

</template>
<script>
export default {
    data(){
        return {
            checked: [],
            checkList: [
                {id: 1, label: '飞机'},
                {id: 2, label: '轮船'},
                {id: 3, label: '汽车'},
                {id: 4, label: '火车'},
            ],
        }
    },
    methods: {
        test(val){
            this.checked = val;
            console.log(this.checked)
        }
    }
}
</script>

打印出的值即为选中的复选框的id的值

[1, 3]

发布时间:2023/06/01

发表评论