v-img can't locate resource from assets folder [duplicate]
Asked Answered
D

2

6

I am having problems displaying a static image located at src/assets/images/logo.png folder with the v-img Vuetify component.

      <v-img src="@/assets/images/rima_logo.png"></v-img>

It doesn't load with Vuetify, but using a plain img tag it does find the resource. Also vscode provides completion for the image relative path so I don't know why vuetify isn't loading it correctly.

Disafforest answered 19/2, 2023 at 20:49 Comment(2)
I think this should work:` :src="require(@/assets/images/rima_logo.png)"`Cinder
Does this answer your question? How to reference static assets within vue javascriptMikiso
E
10

It works on <img> due to the vue compiler feature transformAssetUrls. Vuetify's vite plugin has a preset for this to support vuetify components:

// vite.config.js
import vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'

export default {
  plugins: [
    vue({ 
      template: { transformAssetUrls }
    }),
    vuetify(),
  ],
}

https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin#image-loading

Edgy answered 20/2, 2023 at 15:51 Comment(0)
M
1

You code looks no problem, on condition that you have configured the path alias in your vue.config.js:

 module.exports = {
  ...
  chainWebpack: (config) => {
    config.resolve.alias
      .set('assets', resolve('src/assets'));
    },
};

Vite config:

export default function ({ command }: ConfigEnv): UserConfigExport {
  const isProduction = command === 'build';
  const root = process.cwd();
  return {
    root,
    resolve: {
      alias: [
        // /@/xxxx => src/xxxx
        {
          find: '@',
          replacement: resolve(__dirname, 'src'),
        },
        {
          find: /\/#\//,
          replacement: pathResolve('types') + '/',
        },
        { find: /^~/, replacement: '' },
      ],
    },
    server,
    plugins: createVitePlugins(isProduction),
    build: {
      sourcemap: true,
   },
  };
}

There some other solutions which should also works:

use required

<v-img :src="require(@/assets/images/rima_logo.png)"></v-img>

Import image as a resource:

// template
<v-img :src="rimaLogo"></v-img>

// scripts
import rimaLogo from 'assets/images/rima_logo.png';



 
Mighty answered 20/2, 2023 at 5:9 Comment(3)
I am using Vite with Vue, I don't have a vue.config.js, should I add one with the content you suggested? The second option of importing image as a resource works, thank you!Disafforest
@JonPC, Update vite config in the answer. If you are using vite, you could also check the alias config: vitejs.dev/config/shared-options.html#resolve-alias BTW, if you think this answer helps, please help to vote up.Mighty
Last suggestion works for meSulfate

© 2022 - 2024 — McMap. All rights reserved.