1

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.

JonPC
  • 45
  • 6
  • 1
    I think this should work:` :src="require(`@/assets/images/rima_logo.png`)"` – wittgenstein Feb 19 '23 at 22:28
  • 1
    Does this answer your question? [How to reference static assets within vue javascript](https://stackoverflow.com/questions/47313165/how-to-reference-static-assets-within-vue-javascript) – Neha Soni Feb 20 '23 at 04:45

2 Answers2

4

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

Kael Watts-Deuchar
  • 4,213
  • 1
  • 26
  • 50
0

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';



 
huan feng
  • 7,307
  • 2
  • 32
  • 56
  • 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! – JonPC Feb 20 '23 at 15:11
  • @JonPC, Update vite config in the answer. If you are using vite, you could also check the alias config: https://vitejs.dev/config/shared-options.html#resolve-alias BTW, if you think this answer helps, please help to vote up. – huan feng Feb 21 '23 at 01:11