Valentin Massart
Valentin Massart

Reputation: 45

VueJS : how NOT to concatenate a link url?

I'm at the start of a new project and I'm trying to render a list of links. My links urls are stored in a table under the format "www.sitename.com". They render alright, but when I click on one of them, instead of being redirected to "www.sitename.com", what I get is this: "localhost/8080/www.sitename.com". So, if I understand correctly, it means that VueJS concatenates by default the :href="" with the current url? How do I prevent this?

I solved my issue by hard-coding a 'https://' substring into my Vue component (see below), but I believe there might be better ways to fix this behavior. Any input is welcome.

<template>
  <div :key="link.id">
    <a 
      :href="'https://' + link.url"
      target="_blank"
    >
      {{link.title}}
    </a>
  </div>
</template>

<script>
export default {
  name: "Link",
  props: ["link"]
};
</script>
´´´

Upvotes: 0

Views: 707

Answers (1)

Cianekjr
Cianekjr

Reputation: 384

  1. https://url.spec.whatwg.org/#valid-url-string

A valid URL string must be either a relative-URL-with-fragment string or an absolute-URL-with-fragment string.

  1. https://en.wikipedia.org/wiki/Uniform_Resource_Identifier

    Absolute URL must contain scheme:

    URI

A URI reference is either a URI, or a relative reference when it does not begin with a scheme component followed by a colon (:).

Therefore www.sitename.com is treated like a relative URL.

  1. https://www.contentkingapp.com/academy/urls/faq/absolute-vs-relative/#:~:text=A%20relative%20URL%20is%20a,as%20the%20page%20it's%20on.

A relative URL is a URL that only includes the path. The path is everything that comes after the domain, including the directory and slug. Because relative URLs don't include the entire URL structure, it is assumed that when linking a relative URL, it uses the same protocol, subdomain and domain as the page it's on.

  1. To sum up, path which starts with www is treat as relative url. You want redirect to other domain, so you have to include scheme (e.g. http:, https:).

Upvotes: 1

Related Questions