How to select an HTML element in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to select an HTML element using $refs in Vue.js.

Instead of using a querySelector you can simply assign a ref to an HTML element, e.g. to a list:

<ol ref="list">
  <li v-for="todo in todos">{{ todo.text }}</li>
</ol>

Hi, I'm Renat 👋

 


Now, we can access the “list” element using Vue.js.

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript", done: true },
      { text: "Learn Vue", done: true },
      { text: "Build something awesome", done: true }
    ]
  },
  methods: {},
  mounted() {
    console.log(this.$refs.list)
  }
})

The following output will be printed in the developer’s console:

You can also learn how to call a child function using refs in Vue.js.

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-select-html-element

PS: Make sure you check other Vue.js tutorials, e.g. force reload the current page/component in Vue.js or using Vue.js (Angular/React) for building prototypes.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment