vue觸發(fā)真實的點擊事件跟用戶行為一致問題
vue觸發(fā)真實的點擊事件跟用戶行為一致
<template>
<div>
<button ref="myButton" @click="handleClick">按鈕</button>
</div>
</template>
<script>
export default {
methods: {
handleClick() {
const button = this.$refs.myButton;
// 創(chuàng)建一個鼠標點擊事件
const event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
// 觸發(fā)鼠標點擊事件
button.dispatchEvent(event);
}
}
}
</script>在這個示例中
我們有一個按鈕,并綁定了一個點擊事件處理函數(shù) handleClick。
在 handleClick 方法中,我們首先獲取按鈕元素的引用。
然后,使用 new MouseEvent 創(chuàng)建一個新的鼠標點擊事件,可以設置一些相關的屬性。
最后,通過調(diào)用 dispatchEvent 方法并傳遞創(chuàng)建的事件對象,來觸發(fā)真實的鼠標點擊事件。
請注意,通過 dispatchEvent 方法觸發(fā)的鼠標點擊事件是真實的,它會觸發(fā)與用戶實際點擊按鈕時相同的行為和效果。
vue實現(xiàn)自動觸發(fā)點擊事件
1.使用VUE自定義指令實現(xiàn)
<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');//所以都觸發(fā)一次,
}
}
}3.回顯賦值
el-tree的數(shù)據(jù)是動態(tài)添加的,所以回顯的數(shù)據(jù)一定要在data數(shù)據(jù)追加后再回顯被選中的數(shù)據(jù)
getInfo(){
this.isCheck = true //重點:回顯之前一定要設置為true
this.$nextTick(() => {
this.$refs.tree.setCheckedKeys(this.defKeys) //給樹節(jié)點賦值回顯
this.isCheck = false //重點: 賦值完成后 設置為false
})
}
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

