Vue: add focus on an input when changing a property in the pinia store

71 views Asked by At

I have a component that on click calls a function that does things in the store:

<button @click="this.store.foo()"></button>

And in the store I change this property:

state: () => ({
 focusIn: false,
}),
actions: {
 foo() {
   this.focusIn = true;
 }
}

Now how do I make sure that when I change this focusIn property in the store, it sets the focus to an input in a component other than MyComponent?

2

There are 2 answers

2
Crashh On

you can add a templete ref on the button and use it to trigger the focus() function.

<template>
   <button ref="button" @click="this.store.foo(button)">Button</button>
</template>

<script setup>
const button = ref()
</script>

And in your pinia store

state: () => ({
 focusIn: false,
}),
actions: {
 foo(buttonRef) {
   this.focusIn = true;
   buttonRef.focus()
 }
}
1
MTing On

You can try this:

  1. add "ref" to your input:
    <template> <input ref="my_template_input"> </template>
  1. make it focus when you need:
    this.$refs.my_template_input.focus();