Kayahan Kahrıman
Kayahan Kahrıman

Reputation: 628

VUE3 - Select element on mounted() or created() in a custom component without using "event"

i have a custom input component and i want to select it without clicking on it or something so i cant use "event", i want to select it on created() or mounted()

how can i do that?

<template>
  

    <div class="form-control">
        <label :for="id">
          {{ label }}
        </label>
        <input
          :id="id"
          :type="mode"
          :value="currentValue"
          @input="$emit('update:modelValue', $event.target.value)"
          @focus="pullLabel"
          @blur="pushLabel"
        />
      </div>
    </template>
    
    <script>
    export default {       
    
      created() {
        this.test();
      },     
      
    
      methods: {
        
        test() {
          console.log(this); // -> How could this be like '<input id="title" type="text">'
        },

      },

    };
    </script>

Upvotes: 1

Views: 922

Answers (1)

Kayahan Kahrıman
Kayahan Kahrıman

Reputation: 628

I figured it out myself after 6~ hours of work.

The answer is $refs

I sent a "ref" from parent component like this:

<form ref="settingsForm" @submit.prevent="updateConfig">

Then in methods, i selected all the inputs in form like this: (except submit input)

methods: {
...

focusInput() {
  const inputs = this.$refs.settingsForm.querySelectorAll(
    'input:not([type="submit"])'
  ); // $refs.settingsForm -> comes from the parent element, you can name "settingsForm" whatever you want

  Array.from(inputs).map((e) => {
    if (e.value.length > 0) {
      e.previousElementSibling.classList.add("clicked-input");
    }
  });
},
    
...  
}

By the way, the most important thing is, you have to call the function on mounted() method, not on created()

Upvotes: 1

Related Questions