0

The Code

I have a Vue App with this structures :

  • public
    • img
      • logo.png
  • src

And i have this router.js

const router = new Router({
  mode: "history",
  routes: [
    {
      path: '/',
      redirect: 'dashboard',
      component: UITemplate,
      children: [
        {path: '/dashboard', name: 'dashboard', component: () => import('/views/Dashboard.vue')},
        {path: '/admin/role', name: 'role', component: () => import('/views/Role.vue')},
      ]
    }
  ]
})

And this vue.config.js

module.exports = {
...
   publicPath: '/'
...
}

The Problem

Let's say i want to link an src to an img in UITemplate component. It looks like this

<img :src="/img/brand/logo.png" />

If i try this on localhost:8080/dashboard, the image is perfectly shown. But when i try on localhost:8080/admin/role, the image is not showing.

I looked up in Network Panel and it tries to find the file in this url : localhost:8080/admin/role/img/logo.png

So how to perfectly use the publicPath in Vue so the publicPath will always start from the public folder (without adding /admin/role)? I tried another solutions by adding base to Router, publicPath in webpack.config.js, but it's still not working

  • Can't recall at the moment, so I'm not gonna post it as answer. There are two tricks here: 1) don't start with slash. Starting with slash means append, without means absolute (or is that just with vue router..?). 2) get some loaders (google vue loader). That's a dev dependency, so no extra load on done app. With loaders you do it like `@/folder/image.png` where in config you define `@` (or any other string) to be specific path. See https://vue-loader.vuejs.org/guide/asset-url.html and https://stackoverflow.com/questions/47313165/how-to-reference-static-assets-within-vue-javascript Best of luck – n-smits Dec 26 '20 at 18:50
  • 1
    Thanks man @n-smits, i added vue-loader and it worked. Originally, i actually can set the url to `@/../public/img`, but i manually set an alias to public folder in vue.config and it worked as well. – Luthfi Hizbulloh Dec 27 '20 at 06:54

0 Answers0