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>
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With