vue静态布置图片资源,前端用户可以根据缩略图进行选择,前后端实现代码
上篇文章有些不足和错误.
现在本篇进行改正.
首先前端代码变化不大,唯一就是变量,之前是传的是个变量名字,我们需要拿到图片的名字.
<el-form ref="form" :model="form">
<el-form-item label="编制" prop="bianzhi">
<el-radio-group v-model="form.bianzhi">
<el-radio
v-for="(thumbnail, index) in thumbnails"
:key="index"
:label="thumbnail"
@change="selectedThumbnail = thumbnail">
<el-image :src="thumbnail" fit="cover" :preview-src-list="[thumbnail]">
</el-image>
</el-radio>
</el-radio-group>
</el-form-item>
</el-form>
注意:label和@change部分代码即可.
在 created() 生命周期钩子函数中,使用 require() 函数引入了图片资源,并将其存储在了 thumbnails 数组中,以便在表单中使用。
created() {
this.getList();
this.thumbnails = [
require('@/assets/laboratory/1.png'),
require('@/assets/laboratory/2.png'),
require('@/assets/laboratory/3.png'),
require('@/assets/laboratory/4.png')
]
}
至此前端已经实现可以选择图片的功能了,并且可以看到图片的缩略图.
接下是方法:将相对路径转为绝对路径,然后跟着表单一起传到后端即可.
data里面数组和新增变量的补充:
data() {
return {
thumbnails: ['src/assets/laboratory/1.png', 'src/assets/laboratory/2.png', 'src/assets/laboratory/3.png'],
form: {
bianzhi: '',
shenhe: '',
pizhun: '',
// ...
},
selectedThumbnail: '', // 新增属性
};
},
方法:转路径是重中之重
methods: {
handleSubmit() {
// 将相对路径转为绝对路径,比如当前页面的 URL 是 http://example.com/path/to/page,那么图片的绝对路径就是 http://example.com/src/assets/laboratory/1.png
const absolutePath = new URL(this.selectedThumbnail, window.location.origin).href;
// 调用后端接口,上传图片
this.$axios.post('/upload-image', { image: absolutePath })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
},
// ...
},
就简单的一行:
const absolutePath = new URL(this.selectedThumbnail, window.location.origin).href;
现在已经是绝对路径,快赋值给你的变量跟着form表单传过去吧.
本文纠正了上篇文章的不足,展示了如何在Vue应用中使用el-image组件展示缩略图,让用户选择。在created()钩子中加载图片资源,通过el-radio-group进行选择。当用户变更缩略图时,保存选中的图片名称。在表单提交时,通过newURL转换为绝对路径,然后使用Axios发送到后端。
480

被折叠的 条评论
为什么被折叠?



