Vue中<img>标签图片想实现动态切换时,无法正常显示问题

目录

问题描述

解决办法


问题描述

最近又在写项目,写到点赞这个地方的时候,想要实现一个图片的动态切换。本以为是一个很简单的问题,没想到却出了问题。

首先我们来看看不进行动态切换时的状态:

<img src="../assets/image/踩.svg">

此时的浏览器控制台显示的是这样的:

图片的路径和我们在编辑器中写的是有出入的。

而当我想要是实现动态切换时,我最初的思路是这样的:通过三元运算符加上一个参数进行判断,来达到切换效果。像这样:

<img :src="isTrample ? '../assets/image/踩.svg' : '../assets/image/踩-填充.svg'">

但是结果就是图片无法显示,而浏览器控制台是这样的:

 

路径和我们在编辑器中写的一样了,但是图片却无法显示出来了。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
可以使用Vue动态组件来实现。 在goodslist主页的模板,给product-wrap添加一个@click事件,将点击事件绑定到一个方法handleClick上,方法通过传递参数来决定渲染哪个组件。 ``` <template> <div class="product-wrap" @click="handleClick"> <div class="product" v-for="product in products" :key="product.id"> <img :src="product.image" alt="" > <div> <span>{{ product.name }}</span> <h4>¥{{ product.price }}</h4> </div> </div> </div> </template> <script> import GoodsDetail01 from './GoodsDetail01.vue'; import GoodsDetail02 from './GoodsDetail02.vue'; export default { data() { return { products: [ { id: 1, name: '商品1', price: 100, image: 'img1.jpg' }, { id: 2, name: '商品2', price: 200, image: 'img2.jpg' }, { id: 3, name: '商品3', price: 300, image: 'img3.jpg' }, ], }; }, methods: { handleClick(product) { if (product.id === 1) { // 根据商品id来判断渲染哪个组件 this.$root.$emit('change-component', GoodsDetail01); } else if (product.id === 2) { this.$root.$emit('change-component', GoodsDetail02); } }, }, }; </script> ``` 在主页的script标签,定义两个组件GoodsDetail01和GoodsDetail02,并在methods绑定change-component事件来动态切换组件。 ``` <script> import GoodsDetail01 from './GoodsDetail01.vue'; import GoodsDetail02 from './GoodsDetail02.vue'; export default { components: { GoodsDetail01, GoodsDetail02, }, data() { return { currentComponent: null, }; }, created() { this.$root.$on('change-component', (component) => { this.currentComponent = component; }); }, }; </script> ``` 在主页的模板,使用动态组件来渲染当前的组件。 ``` <template> <div> <div class="product-wrap" @click="handleClick"> <div class="product" v-for="product in products" :key="product.id"> <img :src="product.image" alt="" > <div> <span>{{ product.name }}</span> <h4>¥{{ product.price }}</h4> </div> </div> </div> <component :is="currentComponent"></component> </div> </template> ``` 这样,就可以在点击主页的商品列表图片动态切换到对应的商品详情页,实现了跳转的效果。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值