Vue中动态设置img的src值实现方式
作者:乘风御浪云帆之上
在Vue中动态绑定img的src属性时,需使用v-bind或:语法,确保数据为有效字符串或URL格式,避免编译错误,开发环境通过颜色区分错误类型,有助于快速定位问题
Vue中动态设置img的src值
问题
- 循环li组件时,动态设置img
- 设置img时,src属性报错
src数据格式
"companyImages":[
"http://localhost:8080/cszj/image/image?image=2757dcrz7e0v5stxwqsvd4dk4ezdvvqo",
"http://localhost:8080/cszj/image/image?image=3757dcrz7e0v5stxwqsvd4dk4ezdvvqo"
]错误的做法
<li v-for="(item,idx) in company_images">
<img id="company_image" src="{{item}}"/>
<el-button>删除</el-button>
</li><li v-for="(item,idx) in company_images">
<img id="company_image" src="{{item.toString()}}"/>
<el-button>删除</el-button>
</li><li v-for="(item,idx) in company_images">
<img id="company_image" :src="{{item.toString()}}"/>
<el-button>删除</el-button>
</li><li v-for="(item,idx) in company_images">
<img id="company_image" src="{{company_images[idx]}"/>
<el-button>删除</el-button>
</li><li v-for="(item,idx) in company_images">
<img id="company_image" :src="{{company_images[idx]}"/>
<el-button>删除</el-button>
</li>等等用了{{}}表达式的
正确的做法【:相当于bind:】
<li v-for="(item,idx) in company_images">
<img id="company_image" :src="item"/>
<el-button>删除</el-button>
</li>其实在编译环境下通过颜色是有区别的
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
