项目里经常会用到,在一个多选下拉框里新增一个选择所有的选项,例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
<el-form>
<el-form-item>
<el-select placeholder="请选择活动区域" multiple v-model="citys">
<el-option v-for="item in cities" :label="item.label" :value="item.value" :key="item.value"></el-option>
</el-select>
</el-form-item>
</el-form>
</div>
<script>
new Vue({
el:"#app",
data:{
cities: [
{value: 'Beijing',label: '北京'},
{value: 'Shanghai',label: '上海'},
{value: 'Nanjing',label: '南京'},
{value: 'Chengdu',label: '成都'},
{value: 'Shenzhen',label: '深圳'},
{value: 'Guangzhou',label: '广州'}
],
citys:[]
}
})
</script>
</body>
</html>
渲染如下:
此时可以多选,如果想要选择所有选项时,得一个个去点击,这样不是很方便,我们可以在下拉框里新增一个选择所有的选项,通过watch用几行代码就可以实现与其它选项的互斥来实现一键多选,如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
<el-form>
<el-form-item>
<el-select placeholder="请选择活动区域" multiple v-model="citys">
<el-option label="选择所有" value="all"></el-option>
<el-option v-for="item in cities" :label="item.label" :value="item.value" :key="item.value"></el-option>
</el-select>
</el-form-item>
</el-form>
</div>
<script>
new Vue({
el:"#app",
data:{
cities: [
{value: 'Beijing',label: '北京'},
{value: 'Shanghai',label: '上海'},
{value: 'Nanjing',label: '南京'},
{value: 'Chengdu',label: '成都'},
{value: 'Shenzhen',label: '深圳'},
{value: 'Guangzhou',label: '广州'}
],
citys:[]
},
watch:{
citys:function(val,oldval){
let newindex = val.indexOf('all'),oldindex = oldval.indexOf('all'); //获取val和oldval里all的索引,如果没有则返回-1
if(newindex!=-1 && oldindex==-1 && val.length>1) //如果新的选择里有勾选了选择所有选择所有 则 只直线勾选所有整个选项
this.citys=['all'];
else if(newindex!=-1 && oldindex!=-1 && val.length>1) //如果操作前有勾选了选择所有且当前也选中了勾选所有且勾选数量大于1 则移除掉勾选所有
this.citys.splice(val.indexOf('all'),1)
}
}
})
</script>
</body>
</html>
这样就可以互斥了,效果如下:
挺好用的哈
来源:oschina
链接:https://my.oschina.net/u/4255158/blog/4518364