Vue Page Title - Example 02
by Vinicius Reis
HTML
<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-page-title@beta"></script>
<div id="app"></div>
CSS
body {
background-color: #111;
}
JavaScript
const { createApp, h, ref, computed, onBeforeUnmount } = Vue
const { pageTitle, useTitle } = VuePageTitle
const CAPTAINS = [
'Monkey D. Luffy',
'Trafalgar D. Water Law',
'Eustass Kid',
'Shanks',
'Edward Newgate',
'Charlotte Linlin',
'Capone Bege',
'Gol D. Roger'
]
const getCapitain = () => CAPTAINS[Math.floor(Math.random() * CAPTAINS.length)]
const app = createApp({
setup() {
const current = ref('Capitains')
const color = computed(() => `#${intToRGB(hashCode(current.value))}`)
const { title } = useTitle(current)
const refresh = () => {
current.value = getCapitain()
}
const interval = setInterval(refresh, 5000)
onBeforeUnmount(() => {
clearInterval(interval)
})
return {
title,
color,
current
}
},
render() {
return h('h1', {
style: {
color: this.color
}
}, `🏴☠️ ${this.title}`)
}
})
app.use(pageTitle({
suffix: '- Vue Page Title',
}));
app.mount('#app')
// -----
// from https://stackoverflow.com/a/3426956
function hashCode(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
function intToRGB(i) {
let c = (i & 0x00FFFFFF)
.toString(16)
.toUpperCase();
return "00000".substring(0, 6 - c.length) + c;
}