Vue 3: How to implement a function that modifies all input fields in the DOM?

562 views Asked by At

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');

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?

1

There are 1 answers

3
Деревянко Сергей On
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");