Vue.js is a frontend JavaScript framework primarily used for building Single-Page Applications (SPA). Its routing management is typically handled through vue-router, which is Vue.js's official routing library. While vue-router is commonly used to manage navigation within the same Vue application, such as moving between components, linking to external websites is not directly managed by vue-router.
Method 1: Using the Traditional <a> Tag
The simplest and most straightforward approach is to use a standard HTML <a> tag within a Vue component. For example, to link to Google, you can write the following in your Vue template:
html<template> <div> Visit <a href="https://www.google.com" target="_blank">Google</a> </div> </template>
This method is clear and concise; clicking the link opens the specified external URL in a new browser tab or window.
Method 2: Navigating Programmatically
When you need to handle more complex logic in your Vue.js code to determine navigation to an external website or construct URLs dynamically, use window.open in your methods. For example:
javascript<template> <button @click="goToGoogle">Visit Google</button> </template> <script> export default { methods: { goToGoogle() { const url = "https://www.google.com"; window.open(url, '_blank'); } } } </script>
Here, JavaScript handles the click event, and window.open opens the link in a new tab.
Method 3: Using Environment Variables or Configuration
In large projects where external URLs vary by environment (e.g., development, testing, or production), manage these URLs using environment variables.
javascript<template> <button @click="goToExternalSite">Visit External Site</button> </template> <script> export default { methods: { goToExternalSite() { const baseUrl = process.env.VUE_APP_EXTERNAL_URL; // Read from environment variable window.open(baseUrl, '_blank'); } } } </script>
This method allows flexible URL management across deployment environments by simply adjusting the environment variables.
Conclusion
Although vue-router is a powerful tool for internal routing, for external links, traditional HTML links or JavaScript's window.open method are more direct and appropriate. Choose the method that best fits your specific requirements.