Anthony
Anthony

Reputation: 95

binding dynamic img src in vue

I want to bind my image src dynamically. my template:

<template>
    <div class="item">
        <div class="img">
            <img v-bind:src="getImg" > 
        </div>
    </div>
</template>

I have a computed function:

 getImg(){
            var img=this.project['img'];
            return require(`${img}`); // i am sure img exists
        }

but i got module not found error .

Uncaught (in promise) Error: Cannot find module '../assets/projects/sample.jpg'
    at webpackContextResolve (eval at ./src/components sync recursive ^.*$ (app.js:1247), <anonymous>:15:11)
    at webpackContext (eval at ./src/components sync recursive ^.*$ (app.js:1247), <anonymous>:10:11)
    at Proxy.getImg (ProjectItem.vue?624f:26)
    at ComputedRefImpl.reactiveEffect [as effect] (reactivity.esm-bundler.js?a1e9:42)
    at ComputedRefImpl.get value [as value] (reactivity.esm-bundler.js?a1e9:790)
    at Object.get [as getImg] (runtime-core.esm-bundler.js?5c40:5387)
    at Proxy.render (eval at ./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader-v16/dist/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader-v16/dist/index.js?!./src/components/ProjectItem.vue?vue&type=template&id=210d7dcc&scoped=true&bindings={"project":"props","key":"props","getImg":"options"} (app.js:986), <anonymous>:21:19)
    at Proxy.eval (runtime-core.esm-bundler.js?5c40:1154)
    at renderComponentRoot (runtime-core.esm-bundler.js?5c40:535)
    at componentEffect (runtime-core.esm-bundler.js?5c40:4286)

Upvotes: 1

Views: 1733

Answers (1)

Michal Lev&#253;
Michal Lev&#253;

Reputation: 37793

You need to understand that require() (or import()) is handled by Webpack at build time. Webpack can't execute your code and possibly know what the value at runtime will be. Take a look at the docs (it's about import() but require() is almost same)

Simple fix would be to make only part of the path dynamic so Webpack gets at leas some hint what file should be made available...

Try to replace

return require(`${img}`);

by

return require(`../assets/projects/${img}`);

and store just the file name in the img variable...

Upvotes: 2

Related Questions