Vue DOM image won't show correctly

丶灬走出姿态 提交于 2021-02-05 08:54:28

问题


I'm using the Vue framework and creating an image using the DomUtil.Create function. In this image I want to dynamically write the source to this image. But the image won't show to the user.

I put a normal image on the page using the <img> tag and it works here. Only when creating the DOM element it doesn't work. I put the path hard coded in here so it is certain that the path is correct.

var img = L.DomUtil.create("img", "popUpImg", divImg);
img.src = '@/assets/pictures/1.png';

回答1:


Use require()

When binding to a project path / filename, use require:

require('@/assets/pictures/1.png');

If you use project asset paths and filenames in Vue CLI, Webpack actually renames them while bundling. Vue CLI quietly takes care of this if you use a string path for img src in the template. But in any other situation, you need to manually use Webpack's require to give the correct path and filename at runtime.

- Note: You can npm run build and then check the dist > img folder to see the renaming for yourself. -


Can I use a variable with require()?

When using a variable path/filename, require needs some assistance. You must hard code at least the first portion of the path as a string.

  • For example, this works:
const filename = '1.png';
require('@/assets/pictures/' + filename); // <-- The string is needed
  • This works too:
const path = 'assets/pictures/1.png';
require('@/' + path); // <-- This is good enough too
  • But this would not work:
const fullpath = '@/assets/pictures/1.png';
require(fullpath); // <-- No. Can't infer the path from a variable only

Read more in the Vue Loader docs



来源:https://stackoverflow.com/questions/61317495/vue-dom-image-wont-show-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!