Vue 3 - refs
by skirtle
HTML
<script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script>
<div id="app">
<button @click="showAtTop = !showAtTop">Toggle</button>
<div v-if="showAtTop">
<input ref="inputEl">
</div>
<hr>
<div v-if="!showAtTop">
<input ref="inputEl">
</div>
</div>
JavaScript
const { h } = Vue
const app = Vue.createApp({
render () {
const input = h('input', { ref: (el) => {debugger; return 'inputEl'} })
const children = [
h('button', {
onClick: () => {
this.showAtTop = !this.showAtTop
}
}, 'Toggle')
]
if (this.showAtTop) {
children.push(h('header', [input]))
}
children.push(h('hr'))
if (!this.showAtTop) {
children.push(h('footer', [input]))
}
return h('div', children)
},
data () {
return {
showAtTop: false
}
},
mounted () {
this.logRefs()
},
updated () {
this.logRefs()
},
methods: {
logRefs () {
console.log('$refs.inputEl', type(this.$refs.inputEl))
function type (v) {
return ({}).toString.call(v).slice(8, -1)
}
}
}
})
app.mount('#app')