Using the CDN in Vue

In our Vue app, we're loading some static assets as well. For example, in the toolbar we use the logo.

resources/assets/components/App.vue:

<img class="icon" src="/images/logo.png">

As this is a relative URL it will, by default, point to the web server. If we make it an absolute URL instead, we'd have to hard-code the CDN URL, which is not ideal either.

Let's instead get Laravel to pass the CDN URL in the head of the document. We can do this by simply calling the cdn helper with an empty string.

resources/views/app.blade.php:

<head>
  ...
  <script type="text/javascript">
     ...
     window.cdn_url = "{{ cdn('') }}";
   </script>
</head>

We'll now use a computed property to construct the absolute URL using this global value.

resources/assets/components/App.vue ...

Get Full-Stack Vue.js 2 and Laravel 5 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.