Accessing an element inside a Vuejs component
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.
Here are the steps that worked for me:
- Reference your $ref in the html element:
<p ref = "myref">Welcome to myApp</p>
- Define a boolean variable in the script:
shown = false
- In the update life cycle hook, keep this code:
update(){
if(this.shown){
console.log(this.$refs.myref)
your code
}
}
- Change the boolean to "true" inside your function like the below code:
test(){
this.shown = false
....
some code
....
this.shown = true // this will trigger the code written in the update hook
}
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>