Last active
June 28, 2018 08:35
-
-
Save tdkn/3b043c3b8fc032f8c4fbf5edcb831d12 to your computer and use it in GitHub Desktop.
Vue.js auto-link directive for Tweet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div v-auto-link> | |
{{item.tweet}} | |
</div> | |
</template> | |
<script> | |
export default { | |
data: () => ({ | |
item: { | |
tweet: '@twitter Hello, World! https://twitter.com #twitter' | |
} | |
}), | |
directives: { | |
'auto-link': { | |
inserted(el) { | |
// URL | |
el.innerHTML = el.innerHTML.replace( | |
/(https?:\/\/[a-zA-Z0-9\-_.:@!~*'(¥);/?&=+$,%#]+)/g, | |
'<a href="$1" target="_blank">$1</a>' | |
) | |
// #hashtags or @mentions | |
el.innerHTML = el.innerHTML.replace(/([@#])([\w]+)/gi, (_, p1, p2) => { | |
const text = p1 + p2 | |
const route = p1 === '@' ? p2 : `hashtag/${p2}` | |
return `<a href="https://twitter.com/${route}" target="_blank">${text}</a>` | |
}) | |
} | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment