Vue中如何使用v-bind:src绑定select菜单选中的图片资源
解决方案
你需要补充select的选中值绑定逻辑,具体修改如下:
1. 模板部分改造
<!-- 给select添加v-model绑定选中的图片路径 --> <select v-model="selectedImgPath"> <optgroup v-for="[folder, files] in filteredList" :label="folder" :key="folder"> <!-- 给v-for补充key避免Vue警告 --> <option v-for="img in files" :value="img.path" :key="img.path">{{img}}</option> </optgroup> </select> <span>image here: </span> <!-- 直接绑定存储选中路径的响应式变量即可 --> <img v-bind:src="selectedImgPath" width="150" height="150" alt="预览图" />
2. 脚本部分补充响应式变量
Vue 2 选项式API写法
export default { data() { return { // 初始值可设为空,或者指定默认选中的图片路径 selectedImgPath: '' } } }
Vue 3 组合式API写法
import { ref } from 'vue' // 声明存储选中路径的响应式变量 const selectedImgPath = ref('')
注意事项
如果你的图片是项目内的本地静态资源,路径如果是动态拼接的形式,需要额外用require()(Vue2)或者new URL()(Vue3 + Vite)处理路径,确保构建工具能正确识别资源位置。
内容的提问来源于stack exchange,提问作者Vzupo
相关产品推荐
相关产品推荐

