Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  7] [ 6]  / answers: 1 / hits: 7890  / 2 Years ago, mon, january 17, 2022, 12:00:00

I am trying to implement a component named CamViewMatrix in Vue.js. My requirement is to get the width of CamViewMatrix's parent inside itself (say in created() method of CamViewMatrix) so that I can make some calculations with it (there are some time-based charts that need to be made responsive which is not possible unless an initial value for width is in hand).


<div>
<div class='controller-wrapper'>
...
</div>
<CamViewMatrix v-bind:cameras='cams' />
</div>



I tried assigning an id to its parent and passed the same as a prop to CamViewMatrix, and attempts to getElementById, but it's not able to. Code given below:


<div id='parentid'>
<div class='controller-wrapper'>
...
</div>
<CamViewMatrix v-bind:cameras='cams' parentId='parentid' />
</div>

And inside CamViewMatrix component:


<script>
export default {
name: 'CamViewMatrix',
props: {
parentId: {
type: String,
required: true,
},
...
},
created() {
console.log(document.getElementById(this.parentId)); // 👈️ logs null
...
}
}

With the above code, I am not able to get the parent element (it's logging null).




Have also tried using ref and $parent, but was not able to. Kindly help me with this.


Thanks in advance.


More From » vue.js

 Answers
5

created() is the wrong lifecycle hook to do that.


If you check the lifecycle diagram from the docs: https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram


The element stuff is not yet done (rendered) and only the instance is created.


You most likely what to do that in mounted.


Next, you can access your component's parent via this.$parent and the element via this.$parent.$el.


Check out: https://v2.vuejs.org/v2/api/#Instance-Properties




If you want a specific element from parent, create a ref and access it like:


this.$parent.$refs.refNameYouAdded


If it's a Vue component, then it'd be a Vue instance so you need to access $el again:


this.$parent.$refs.refNameYouAdded.$el


otherwise if it's a HTML element, then no need to do that.




most of the time, the above answers work but sometimes if your parent component does things like moving elements somewhere else then it might not be accurate.


as mentioned in the comment, you can still access the correct parent element by doing:


this.$el.parentElement


[#470] Thursday, January 13, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keyonna

Total Points: 521
Total Questions: 104
Total Answers: 96

Location: Samoa
Member since Tue, May 3, 2022
2 Years ago
;