Liga
Liga

Reputation: 3439

Can't get the $ref of a child inside a component. Getting undefined error

I'm using Vue.js and I am trying to get the width of both ref=“mybtn” and ref=“confirmpopover” but I can’t get the width of ref=“confirmpopover”. I can’t understand why, it is saying undefined.

Trying to get getBoundingClientRect of undefined.

export default {
    template: `
    <div @click="openPopover" ref="mybtn">
        <ml-confirm-popover ref="confirmpopover" />
    </div>
`,

methods: {
    openPopover() {
        // result: 200
        console.log( this.$refs.mybtn.getBoundingClientRect().width )

        // result Trying to get getBoundingClientRect of undefined.
        console.log( this.$refs.confirmpopover.getBoundingClientRect().width )
    }
}

Upvotes: 1

Views: 967

Answers (1)

yuriy636
yuriy636

Reputation: 11681

From the ref docs:

If used on a plain DOM element, the reference will be that element; if used on a child component, the reference will be component instance

So if you want the actual DOM element, you have to access the $el inside of the ref:

console.log( this.$refs.confirmpopover.$el.getBoundingClientRect().width )

Upvotes: 3

Related Questions