Blog>
Snippets

Accessibility with Template Refs

Use template refs to enhance accessibility by programmatically managing focus among interactive elements on the page.
// A Vue.js component example
new Vue({
  el: '#app',
  data: {
    isActive: false
  },
  methods: {
    setFocus(refName) {
      this.$refs[refName].focus();
    },
    toggleActiveState() {
      this.isActive = !this.isActive;
      const refName = this.isActive ? 'activeInput' : 'inactiveInput';
      this.setFocus(refName);
    }
  }
});
This code snippet is an example of a Vue.js component using template refs. It declares a method 'setFocus' to focus a DOM element by referring to it by its ref name. Another method 'toggleActiveState' is used to toggle the state of 'isActive' and programmatically move focus between two inputs depending on the state.
// HTML template
<div id="app">
  <button @click="toggleActiveState">Toggle Active State</button>
  <input ref="activeInput" type="text" v-show="isActive" placeholder="Active Input">
  <input ref="inactiveInput" type="text" v-show="!isActive" placeholder="Inactive Input">
</div>
This HTML template shows a 'Toggle Active State' button that, when clicked, will call the 'toggleActiveState' method defined in the Vue instance. It also contains two input fields that show or hide based on the 'isActive' data property, each with a ref attribute that corresponds to the names used in the 'setFocus' method.