给el-select多选模式下tag 绑定点击事件
怎么给多选模式下的下拉框绑定事件呢?
因为下拉框组件内部是无法修改的。
给的插槽是用来优化option里的内容,而不是tag组件的
使用我们只能获取dom继续操作
select 多选模式下tag展现多选内容。
tag 没有点击事件。需要操作dom来手动绑定
下面是代码思路
// select dom
<el-select ref="select">
//利用dom
this.$refs.select.$refs.tags.childNodes[1].children.forEach((e, i) => {
e.onclick = (clickEvent) => {
// 这里写点击后的事件()
// e.textContent 为tag的文本内容
clickEvent.stopPropagation(); // 防止冒泡事件
};
});
为了更清楚理解~!
HTML代码,直接粘贴到 codepen 就是 element ui里的在线运行
制作
HTML
<script src="//unpkg.com/vue@2/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.15.13/lib/index.js"></script>
<div id="app">
<template>
<div>
<el-select ref="select" @change="aa" v-model="value1" multiple placeholder="请选择">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
<el-select
v-model="value2"
multiple
collapse-tags
style="margin-left: 20px;"
placeholder="请选择">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</div>
</template>
</div>
css
@import url("//unpkg.com/element-ui@2.15.13/lib/theme-chalk/index.css");
js
var Main = {
data() {
return {
options: [{
value: '选项1',
label: '黄金糕'
}, {
value: '选项2',
label: '双皮奶'
}, {
value: '选项3',
label: '蚵仔煎'
}, {
value: '选项4',
label: '龙须面'
}, {
value: '选项5',
label: '北京烤鸭'
}],
value1: ["选项2"],
value2: []
}
},
methods: {
aa(){
this.$nextTick(() => {
const tags = this.$refs.select.$refs.tags;
if (tags) {
const children = tags.childNodes[1].children;
for (let i = 0; i < children.length; i++) {
const child = children[i];
child.onclick = (clickEvent) => {
// 这里写点击后的事件()
console.log(clickEvent);
const index = Array.prototype.indexOf.call(children, child);
console.log('点击的标签索引:', index);
// child.textContent 为 tag 的文本内容
clickEvent.stopPropagation(); // 防止冒泡事件
};
}
}
});
}
},
mounted() {
this.$nextTick(() => {
const tags = this.$refs.select.$refs.tags;
if (tags) {
const children = tags.childNodes[1].children;
for (let i = 0; i < children.length; i++) {
const child = children[i];
child.onclick = (clickEvent) => {
// 这里写点击后的事件()
console.log(clickEvent);
// child.textContent 为 tag 的文本内容
clickEvent.stopPropagation(); // 防止冒泡事件
};
}
}
});
}
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')