1

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?

NicOwen
  • 171
  • 1
  • 3
  • 8

1 Answers1

1
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");
  • Thanks! But with `this.$el.querySelectorAll('input')` I'm getting *TypeError: this.$el.querySelectorAll is not a function* in console ... but it’s actually working and outputs the error **after** my doSomething(). What I'm doing wrong here? – NicOwen May 25 '21 at 14:17
  • it works for me perfect, maybe you do something wrong? https://codesandbox.io/s/wonderful-cannon-ufy9k?file=/src/main.js – Деревянко Сергей May 26 '21 at 12:21
  • depending on your template, this.$el might not be referring to a real dom node hence you might not be able to invoke querySelectorAll on it. This is mainly due to the support for multiple roots component. To properly get hold of the reference to a real dom node, you should use **Template Refs** – Xinchao Jun 01 '21 at 19:25