[Vuejs]-How to focus on a specific input text after the component is rendered?

0👍

For few days of research and thorough testing and observation on DOM behavior on how vue.js renders component and of course basing on the suggestions from other folks on this thread. I realized you can’t really focus in the created/mounted properties on a specific index of an element within the for loop particulary in this case the input text element if the data being fetch to bind on the component is coming from the server due to its asynchronous behavior and you have to wait until the component is completely rendered. So I found a solution at least on my case to use a dynamic watcher either in the created or mounted properties and set a dummy or duplicate data properties for the default change of the data properties for the purpose of only to activate the watcher to focus on the specific element after the component has been rendered. This how it looks like. Hope this help to folks that encountering the same scenario as me.

created() {           
            this.GetContentDetails();
            this.$watch('commentItems2', function () {
                this.$nextTick(() => {
                    this.$refs.newRep[mapCredential.state.index2].focus();
                });
            });
        },

methods: {
 async GetComment2() {
                let testRes =
                    await axios.get('myUrl/api/GetContent/GetComments')
                        .then(this.GetReply2())
                        .catch(error => console.log(error));
                this.commentItems = testRes.data;
                this.commentItems2 = testRes.data;
            },
}

1👍

From what I understood, you want to focus a textarea after fetching some data, that said trying to focus inside the mounted method wont work because you can’t tell if the data has been fetch and the textareas already exist in the DOM.

So the best way to do this is to focus after being sure the data has been fetched, inside the then callback.

new Vue({
  el: '#app',
  
  data: {
    posts: [],
    index: 3 // Change this to focus whatever textarea you want
  },
  
  mounted () {
    this.fetchItems();
  },
  
  methods: {
    fetchItems () {
      const url = 'https://jsonplaceholder.typicode.com/posts'

      axios.get(url).then(response => {
        this.posts = response.data
        
        this.$nextTick(_ => {
          this.$refs.newInp[this.index].focus()
        })
      })
    }
  }
});
<div id="app"> 
  <div v-for="(post, index) in posts" :key="post.id">
    <textarea class="reply-commented" ref="newInp" v-text="post.body"></textarea>
  </div> 
</div>



<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Leave a comment