Skip to content

Instantly share code, notes, and snippets.

@m4n1ok
Created May 7, 2021 10:10
Show Gist options
  • Save m4n1ok/7287c7bc9b842d48a3224ac42b55df89 to your computer and use it in GitHub Desktop.
Save m4n1ok/7287c7bc9b842d48a3224ac42b55df89 to your computer and use it in GitHub Desktop.
Vue.js Component debug frame mixin
export default {
data() {
return {
debugEnabled: true,
debugFrame: null
}
},
methods: {
registerEvents() {
this.$el.addEventListener('mouseenter', this.showDebug)
this.$el.addEventListener('mouseleave', this.hideDebug)
},
disposeEvents() {
this.$el.removeEventListener('mouseenter', this.showDebug)
this.$el.removeEventListener('mouseleave', this.hideDebug)
},
showDebug() {
if (this.debugFrame) return
this.$el.style.position = 'relative'
this.debugFrame = document.createElement('div')
const styles = {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: 999999,
backgroundColor: 'rgba(0, 125, 255, 0.5)',
padding: '20px'
}
Object.keys(styles).forEach((property) => {
this.debugFrame.style[property] = styles[property]
})
let props = ''
/**
<div><strong>Value:</strong> <code>${JSON.stringify(
this.$props[prop]
)}</code></div>
*/
Object.keys(this.$props).forEach((prop) => {
props += `
<div style='font-size: 9px; padding: 10px; border: 1px solid'>
<div><strong>Name:</strong> ${prop}</div>
<div><strong>Type:</strong> ${typeof this.$props[prop]}</div>
</div>
`
})
this.debugFrame.innerHTML = `
<div style='font-size: 12px; flex-grow: 1;'>
<strong style='font-weight: 700;'>Component Name</strong>
<div>${this.$options.name}</div>
<strong style='font-weight: 700;'>Props</strong>
<div style='display: flex; flex-wrap: wrap;'>
${props}
</div>
</div>
`
this.$el.appendChild(this.debugFrame)
},
hideDebug() {
this.$el.style.position = ''
if (this.debugFrame) {
this.debugFrame.remove()
this.debugFrame = null
}
}
},
mounted() {
this.$nextTick(() => {
if (this.debugEnabled) {
this.registerEvents()
}
})
},
beforeDestroy() {
this.hideDebug()
this.disposeEvents()
},
watch: {
debugEnabled: (active) => {
if (active) {
this.registerEvents()
} else {
this.disposeEvents()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment