Reputation: 65
When i use require in Vue 3, on vue 2 all works
<img :src="require('./img/1.png')" />
I get error:
[Vue warn]: Unhandled error during execution of render function
at <Creator key=1 >
at <Character>
at <App>
Uncaught ReferenceError: require is not defined
at Proxy._sfc_render (creator.vue:14:24)
at renderComponentRoot (runtime-core.esm-bundler.js:895:44)
at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:5059:57)
at ReactiveEffect.run (reactivity.esm-bundler.js:185:25)
at setupRenderEffect (runtime-core.esm-bundler.js:5185:9)
at mountComponent (runtime-core.esm-bundler.js:4968:9)
at processComponent (runtime-core.esm-bundler.js:4926:17)
at patch (runtime-core.esm-bundler.js:4518:21)
at mountChildren (runtime-core.esm-bundler.js:4714:13)
at mountElement (runtime-core.esm-bundler.js:4623:17)
Just text text text text
Upvotes: 3
Views: 11319
Reputation: 418
If I understand the Vite documentation correctly, you should be able to do something like this:
<img :src="imageSrc" />
...
<script>
...
export default {
...
computed: {
imageSrc() {
return new URL(`./img/${selectedItem}.png`, import.meta.url).href;
}
}
}
</script>
Upvotes: 8
Reputation: 6909
require
is a webpack specific feature to handle assets import.
Using vite, it's done differently: https://vitejs.dev/guide/assets.html#importing-asset-as-url
With the vue vite plugin (that you certainly are using), you can just use a relative or absolute path inside :src=""
and vite will convert it to a dynamic import under the hood. So it's transparent for you.
<img src="./imgs/cat.jpeg" width="300px" height="50px">
<img src="~/assets/dog.jpg" width="300px" height="50px">
Upvotes: 1