简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM