如何跟踪表单中的焦点元素

我是 vuejs 的新手,我想知道在表单中跟踪最新的焦点输入/文本区域以便以编程方式从父组件修改它们的值的最佳方法是什么。


例子


Form

  Input1

  Input2 -> focused

  Textarea

Button (onclick -> appends "hello" to the focused input)


MMMHUHU
浏览 113回答 1
1回答

慕森卡

回答:您可以创建一个跟踪当前聚焦/最后聚焦的input元素的数据属性。在下面的示例中,这称为current_focus。为此,您可以使用该focus事件 - 但由于focus不会冒泡,您必须input手动将其应用于每个单独的元素。focusin向父级提供事件处理程序更容易。与 不同focus,此事件将 DOM 从任何子级向上冒泡到其父级。这允许您利用事件委托模式。事件委托意味着您将一个处理程序应用于事件的父级,然后根据事件源执行某些操作。这意味着当我们收到一个focusin事件时,我们可以简单地检查焦点元素是否是一个input元素,然后更新我们的数据属性(current_focus)代码沙盒示例:https://codesandbox.io/s/focus-handler-vzip0代码示例:焦点演示.js<template>&nbsp; <div v-on:focusin="updateFocus">&nbsp; &nbsp; <input name="one">&nbsp; &nbsp; <br>&nbsp; &nbsp; <input name="two">&nbsp; &nbsp; <br>&nbsp; &nbsp; <input name="three">&nbsp; &nbsp; <br>&nbsp; &nbsp; <button @click="handleClick">Add Text To Focused</button>&nbsp; </div></template><script>export default {&nbsp; name: "FocusDemo",&nbsp; data: function() {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; current_focus: undefined&nbsp; &nbsp; };&nbsp; },&nbsp; methods: {&nbsp; &nbsp; updateFocus: function(e) {&nbsp; &nbsp; &nbsp; let element = e.target;&nbsp; &nbsp; &nbsp; if (element.matches("input")) {&nbsp; &nbsp; &nbsp; &nbsp; this.current_focus = element;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; &nbsp; handleClick: function(e) {&nbsp; &nbsp; &nbsp; if (this.current_focus) {&nbsp; &nbsp; &nbsp; &nbsp; this.current_focus.value = "Button was clicked!";&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }};</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript