Reputation: 3885
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>
Upvotes: 23
Views: 36610
Reputation: 3861
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.
Upvotes: 43
Reputation: 949
Here are the steps that worked for me:
<p ref = "myref">Welcome to myApp</p>
shown = false
update(){
if(this.shown){
console.log(this.$refs.myref)
your code
}
}
test(){
this.shown = false
....
some code
....
this.shown = true // this will trigger the code written in the update hook
}
Upvotes: 2
Reputation: 27174
VueJS 1.x
You're probably easier off using the v-el
directive, which allows you to map elements in your component to an vm property on this.$els
.
Also, AFAIK, you shouldn't combine the template
property with templates in the .vue
file (assuming you are using .vue
files, of course).
<template>
<ul class="list-group" id="criteria" v-el:criteria v-for="item in criteria">
<li class="list-group-item">{{ item.name }}</li>
</ul>
</template>
<script>
export default {
data() {
return {
criteria: []
}
},
ready() {
console.log(this.$els.criteria);
},
methods: {},
};
</script>
Upvotes: 17