Accessing subcomponents via ref in vu 2.5.2 with typescript 2.4.2

297 views Asked by At

I ran into a little problem trying to access subcomponents in vue 2.5.2 while using Typescript 2.4.2.

I am trying to access a Keen UI UiSelect component by adding it to $ref with the ref="selectfield" attribute and then access it in my Vue component with this.$refs.selectfield. The UI-Select component is unrendered with the v-if="showSelect" directive.

onClickSpan(){
    showSpan = false;
    showSelect = true;
    console.dir(this.$refs);
    console.dir(this.$refs.selectfield);
}

I have referenced two different elements with ref. I have already tried outputting this.$refs in the console and the Object selectfield is definitely there:

>{…}
|>  currentNumField: <div style="width: 100%;">
|>   selectfield: Object { _uid: 32, _isVue: true, "$options": {…}, … }
|>   __proto__: Object { … } 

undefined

Unfortunately trying to access it will always tell me that this.$refs.selectfield is undefined. I am pretty new to Vue and Typescript and just don't know what could be causing this problem.

Thank you for your time.

2

There are 2 answers

1
Jeremy Walters On

You must give a little more information please. Look at the example https://jsfiddle.net/Jubels/50wL7mdz/78450/

this.$refs.paraG would return the node.

this.$refs.custom would return the vue component

<p ref="paraG">{{ message }}</p>

<custom-component ref="custom">{{ message }}</custom-component>

Hope this clear any uncertainty

0
R.Frix On

I am not certain where the problem came from, but for everyone having similar issues here is a possible solution:

Use v-show instead of v-if.

It seems as though the problem is related to the way the DOM is rendered by using v-if. The ref to the DOM Element is added to the $refs attribute of my component, but the variable $refs.mycomponent is empty since an element that is hidden with v-if is not only not rendered but not even added to the DOM.

I tried using a delay after making the object visible, but that did not solve the problem. I can only assume that this is due to an issue with typescript that doesn't properly update the $refs attribute whenever the DOM is rerendered since this works with v-if when I am only using Vue.