Reputation: 165
I'm trying to get a dom element by id using vuejs. The problem is I don't know how to access this element. I'm using this.$refs. When I write console.log(this.$refs) I see the following:
But when I write console.log(this.$refs.gauge2) I see undefined. Does anyone know how to access this element? This is my code:
<script lang="ts">
import Vue from 'vue'
var Gauge = require('svg-gauge')
export default Vue.extend({
components: {
},
created(){
console.log(this.$refs)
console.log(this.$refs.$gauge2)
var element = this.$refs.gauge2
var gauge2 = Gauge(
element, {
min: -50,
max: 50,
dialStartAngle: 180,
dialEndAngle: 0,
value: 50
}
);
},
})
</script>
<template>
<div class="wrapper">
<div id="gauge2" ref="gauge2" class="gauge-container two">
<span class="label">.two</span>
</div>
</div>
</template>
Thank you
Upvotes: 0
Views: 4160
Reputation: 980
Your problem is that you are trying to access a ref from the created method which is called before the template has rendered. You can access refs only after the template has been rendered, I would suggest using the mounted function.
For more information:
EDIT Take a look at this picture, taken from the official Vue.js Website:
Upvotes: 1
Reputation: 2856
You can do it with:
this.$refs.gauge2.$el.id
and by changing the trigger to the mounted() hook:
Upvotes: 0
Reputation: 165
I fixed it changing the method created by mounted. Now it works thanks!
Upvotes: 0
Reputation: 150
this.$refs.gauge2.id
if you get undefined
value, the reason is that the console.log
command was run before assigning ref
(gauge2) to this element.
Upvotes: 0