Home > Mobile >  How to pass the src attribute of the img tag to the child component through the parent component in
How to pass the src attribute of the img tag to the child component through the parent component in

Time:12-01

I have a parent component and a child component, and I want to pass a src attribute to the child component via defineProps to make it display the image.

Below is my parent component code:

<script setup>
import item from "./item.vue";
const items=[
  {
    id:0,
    img:'../assets/2.png',
    name:'秘塔写作猫',
    des:'码文章必备工具'
  },
  {
    id:1,
    img:'../assets/2.png',
    name:'AdblockPlus广告拦截',
    des:'最流行的广告拦截拓展程序'
  },
  {
    id:2,
    img:'../assets/3.png',
    name:'Tampermonkey油猴脚本',
    des:'码文章必备工具'
  },
  {
    id:3,
    img:'../assets/4.png',
    name:'蔚蓝主页',
    des:'个性化简洁风格浏览器主页'
  },
  {
    id:4,
    img:'../assets/5.png',
    name:'ABCD PDF',
    des:'完全免费在线PDF压缩转换工具'
  },
  {
    id:5,
    img:'../assets/6.png',
    name:'ASO谷歌商店工具',
    des:'洞悉竞品下载、评论等核心数据'
  },
]
</script>

<template>
  <div id="ain">
    <div id="head">
      <h4>站长推荐</h4>
      <a>查看全部</a>
    </div>
    <div id="body">
      <item v-for="item in items" :key="item.id"  :img="item.img" :name="item.name" :des="item.des">
      </item>  
    </div>
  </div>
</template>

Below is my subcomponent code:

<script setup>
  defineProps(['img','name','des'])
</script>

<template>
  <div id="item">
    <div>
        <img src="img">
        <p>{{name}}</p> 
        <p id="detail">{{des}}</p>
    </div>
  </div>
</template>

This error is displayed in the console:GET http://127.0.0.1:5173/assets/2.png 404 (Not Found)

I think it's a problem with passing parameters, but I don't know how to modify it, thank you all.

CodePudding user response:

There are two solutions 1.You can use an absolute path 2.Put your image in the public path under the root directory

CodePudding user response:

It looks like you are using Vite and there are a few options to reference images:

  1. Use import statements for images to obtain the image URL
import imgUrl from './assets/img.png'
document.getElementById('hero-img').src = imgUrl
  1. Place images inside public folder and reference using /. For example if all images are contained inside public/img then the URL would be /img.

  2. Try new URL(url, import.meta.url) although this does not work with SSR

Number 2) is probably the easiest if these images won't be updated.

Reference: https://vitejs.dev/guide/assets.html

  • Related