vue触发真实的点击事件跟用户行为一致
<template> <div> <button ref="mybutton" @click="handleclick">按钮</button> </div> </template> <script> export default { methods: { handleclick() { const button = this.$refs.mybutton; // 创建一个鼠标点击事件 const event = new mouseevent('click', { view: window, bubbles: true, cancelable: true }); // 触发鼠标点击事件 button.dispatchevent(event); } } } </script>
在这个示例中
我们有一个按钮,并绑定了一个点击事件处理函数 handleclick。
在 handleclick 方法中,我们首先获取按钮元素的引用。
然后,使用 new mouseevent 创建一个新的鼠标点击事件,可以设置一些相关的属性。
最后,通过调用 dispatchevent 方法并传递创建的事件对象,来触发真实的鼠标点击事件。
请注意,通过 dispatchevent 方法触发的鼠标点击事件是真实的,它会触发与用户实际点击按钮时相同的行为和效果。
vue实现自动触发点击事件
1.使用vue自定义指令实现
<el-tree :check-strictly="ischeck" ref="tree" :data="data" show-checkbox node-key="detectorid" :default-expanded-keys="[]" default-expand-all :default-checked-keys="defkeys" :expand-on-click-node="false" :props="defaultprops" @check-change="handlecheckchange"> <span class="custom-tree-node" slot-scope="{ node, data }"> <span> <i class="iconfont icon-jianceqi" v-if="data.isdet"></i> <i v-else style="color:#f19f00;margin-right:10px;" class="iconfont icon-24gf-folder"></i> {{ node.label }} <!-- <i class="iconfont fr icon-gengduo1"></i> --> </span> <span> <el-button v-if="data.itemsnumber > 0 && data.isshow" type="text" size="mini" v-trigger class="wlh-textcolor-red" @click="() => append(data)"> 查看检测器 </el-button> <!-- <el-button type="text" size="mini" @click="() => remove(node, data)"> delete </el-button> --> </span> </span> </el-tree>
methods(){ append(data) { this.getdetelistfromgroup(data.organizationid, () => { this.checklist.foreach(item => { const newchild = { organizationid: item.detectorid, detectorid: item.detectorid, organizationname: item.detectorname, children: [], isdet: true }; if (!data.children) { this.$set(data, "children", []); } data.children.push(newchild); this.getpolicyone(); }); }); // data = object.assign({},data,{isshow:false}) data.isshow = false; } },
2.指令
directives: { trigger: { inserted(el, binging) { // console.log(el) // el.click() $(el).trigger('click');//所以都触发一次, } } }
3.回显赋值
el-tree的数据是动态添加的,所以回显的数据一定要在data数据追加后再回显被选中的数据
getinfo(){ this.ischeck = true //重点:回显之前一定要设置为true this.$nexttick(() => { this.$refs.tree.setcheckedkeys(this.defkeys) //给树节点赋值回显 this.ischeck = false //重点: 赋值完成后 设置为false }) }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论