Vue 3:如何实现修改DOM中所有输入字段的功能? [英] Vue 3: How to implement a function that modifies all input fields in the DOM?
本文介绍了Vue 3:如何实现修改DOM中所有输入字段的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Vue 的新手,想为所有输入字段添加一个 onfocus 函数.当我使用 mixin 时,每次挂载组件时都会调用该函数.
I'm new to Vue and want to add an onfocus function to all input fields. When I use mixin, the function is called every time a component is mounted.
createApp(App).mixin({
mounted() {
myFunction() {
document.querySelectorAll('input').doSomething()
}
}
}).mount('#app');
这是有道理的,也是我想要的,因为新添加的输入字段也应该受到影响.但是每次挂载组件时,该函数都会遍历整个 DOM,对吗?我想避免对已经具有 onfocus 功能的字段进行不必要的迭代.那么做这样的事情的最佳实践是什么?
That makes sense and is in generally what I want, because newly added input fields should be affected, too. But then the function would iterate through the whole DOM every time a component is mounted, right? I want to avoid unnecessary iteration for fields that already have the onfocus function. So what would be best practice to do something like this?
推荐答案
import { createApp, h } from "vue";
import App from "./App.vue";
const app = createApp({
render: () => h(App)
});
app.mixin({
methods: {
myFunction() {
this.$el.querySelectorAll("input").forEach((el) => {
alert(el.getAttribute("name"));
});
}
},
mounted() {
this.myFunction();
}
});
app.mount("#app");
这篇关于Vue 3:如何实现修改DOM中所有输入字段的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文