0

I'm looking to run a function when the state changes in my Vue app. In my component I'm able to get the boolean state of isOpen. I'm looking to run a function that adds focus to my form input when the modal opens and isOpen is set to true. I've tried using a watcher but with no luck. I'm opening my modal by calling :class="{ 'is-open': search.isOpen }" in the html and showing it via css. Any help would be most appreciated.

data() {
    return {
      isFocussed: this.$store.state.search,
      //checks the state of isOpen?
    }
  },

  computed: {
    search() { return this.$store.state.search },
  },

  watch: {
    isFocussed() {
     this.formfocus()
    },
  },

  methods: {
    formfocus() {
      document.getElementById('search').focus()
    },
0

2 Answers 2

1

please check my snippet which shows the good way to work in Vue.js, you can work with refs which is very helpful instead of document.getElementById()

new Vue({
  el: '#app',
  data: {
    isOpen: false,
  },
  computed: {
    
  },
  watch: {
    isOpen(){
      if(this.isOpen){
        this.$nextTick( function () {
            this.formfocus();
          }
        );
      }
    }
  },
  methods: {
    formfocus(){
      this.$refs.search.focus();
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>

<div id="app">
  <button v-on:click="isOpen = !isOpen">show modal</button>
  <div v-if="isOpen">
    <input ref="search" type="text" placeholder="search">
  </div>
</div>

EDIT: i have added a conditional if on the watch, i hope this solves the problem

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Zouheir for this. However I'm getting 'warning Unexpected unnamed function' error from the $nextTick line?
0

I am not sure what your template looks like but here is how I set focus on a conditional element.

element

<input type="text" class="search-input" v-model="search" :class="{'collapsed-search': hideInput}" placeholder="Enter keyword" ref="search">

notice the ref="search" on the input.

here is the method when the input condition is true

toggleSearch() {
  this.hideInput = !this.hideInput
   this.search = ''
   setTimeout(() => {
      this.$refs.search.focus()
  }, 1000)
}

this.$refs.search.focus() is called after the element has been fully created which is the purpose of the setTimeout

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.