1

#Nuxt.js 动态绑定img

 2 years ago
source link: https://xmanyou.com/nuxt-js-bind-image-src-dynamically/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
3 December 2021 / Nuxt.js

#Nuxt.js 动态绑定img

在Nuxt.js项目中,有时候需要为image绑定指定src。

image_src = "~/assets/img/image.png"

以下两种做法都会报错:

  • 错误做法1
   <img
     :src="image_src"
     width="70px"
     height="80px"
   />

错误:
图片无法展示,路径错误。

  • 错误做法2
   <img
     :src="require(`${image_src}`)"
     width="70px"
     height="80px"
   />
 ERROR  [Vue warn]: Error in render: "Error: Cannot find module '~/assets/img/image.png'"

对比官方文档中的示例:

https://nuxtjs.org/docs/directory-structure/assets/

参考官方示例

<img :src="require(`~/assets/img/${image}.jpg`)" />
image_src="image.png"
   <img
     :src="require(`~/assets/${image_src}`)"
     width="70px"
     height="80px"
   />

问题就解决了。

看起来这是因为nuxt.js中,路径~是个特殊路径,需要在编译阶段进行解析,无法在客户端进行。

阿斌

Read more posts by this author.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK