Created
April 16, 2020 02:42
-
-
Save ty4z2008/740161399c48c4f3507b637400a1a853 to your computer and use it in GitHub Desktop.
use js simulate click and input in react or vue.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/**simluate click in react */ | |
function simulateClick(element) { | |
if (element instanceof jQuery) { | |
element = element[0] | |
} | |
const mouseClickEvents = ['mousedown', 'click', 'mouseup'] | |
console.log('[spirit] simulate click:', element) | |
mouseClickEvents.forEach(mouseEventType => | |
element.dispatchEvent( | |
new MouseEvent(mouseEventType, { | |
view: window, | |
bubbles: true, | |
cancelable: true, | |
buttons: 1 | |
}) | |
) | |
) | |
} | |
/**simulate input in react */ | |
function simulateInput(element, val) { | |
if (element instanceof jQuery) { | |
element = element[0] | |
} | |
let input = element | |
let lastValue = input.value | |
input.value = val | |
let event = new Event('input', { | |
bubbles: true | |
}) | |
let keyPress = new KeyboardEvent('keyup', { | |
bubbles: true, | |
key: 'enter' | |
}) | |
// hack React15 | |
event.simulated = true | |
// hack React16 | |
let tracker = input._valueTracker | |
if (tracker) { | |
tracker.setValue(lastValue) | |
} | |
input.dispatchEvent(event) | |
input.dispatchEvent(keyPress) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Useage:
simulateClick($("#app"))
simulateInput($("#app"),'value')