Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an element inside a Vuejs component

Tags:

I'm trying to access an element from the dom from within my Vue component but I just get 'null'. If I go into dev tools and try I can access it. I'm assuming it's a scoping issue but I can't find the answer.

<template>     <ul class="list-group" id="criteria" v-for="item in criteria">         <li class="list-group-item">{{ item.name }}</li>     </ul> </template>  <script>     export default {         template: "report-criteria",         data() {             return {                 criteria: []             }         },         ready() {             console.log(document.getElementById('criteria'));         },         methods: {},     }; </script> 
like image 299
bencarter78 Avatar asked Apr 29 '16 11:04

bencarter78


People also ask

How do I reference an element in Vue?

Refs are Vue. js instance properties that are used to register or indicate a reference to HTML elements or child elements in the template of your application. If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance.

What is REF () in Vue?

ref() # Takes an inner value and returns a reactive and mutable ref object, which has a single property . value that points to the inner value.


1 Answers

The answer posted by @nils is for VueJS 1.x. The v-el directive was removed in newer versions. It was replaced by ref attribute.

To achieve that same result in VueJS 2.x, you should do the following instead:

<template>   <ul class="list-group" id="criteria" ref="criteria" v-for="item in criteria">     <li class="list-group-item">{{ item.name }}</li>   </ul> </template>  <script>   export default {     data() {       return {         criteria: []       }     },     mounted() {       console.log(this.$refs.criteria);     },     methods: {},   }; </script> 

You may find more info about that change in VueJS docs.

like image 189
Gustavo Straube Avatar answered Oct 03 '22 01:10

Gustavo Straube