简体   繁体   English

Vuejs 根据选择绑定图片

[英]Vuejs bind images based on selection

I want to have an unlimited amount images that bind to the page based on how many are selected.我希望根据选择的数量将无限数量的图像绑定到页面。 In the example, I manually added 3, and manually created each method for them.在示例中,我手动添加了 3 个,并为它们手动创建了每个方法。 But is there a way to set this up so that it will generate the correct method with the right variable information for each without having to manually do each time?但是有没有办法设置它,以便它为每个生成具有正确变量信息的正确方法,而不必每次都手动执行? If I have one input box where I can select more than 1 image...and it auto-generate the correct methods would be ideal如果我有一个输入框,我可以在其中 select 超过 1 张图像......并且它会自动生成正确的方法将是理想的

 new Vue({ el: '#app', data() { return { url: null, url2: null, url3: null, } }, methods: { onFileChange(e) { const file = e.target.files[0]; this.url = URL.createObjectURL(file); }, onFileChange2(e) { const file = e.target.files[0]; this.url2 = URL.createObjectURL(file); }, onFileChange3(e) { const file = e.target.files[0]; this.url3 = URL.createObjectURL(file); } } })
 body { background-color: #e2e2e2; } #app { padding: 20px; } #preview { display: flex; justify-content: center; align-items: center; } #preview img { max-width: 100%; max-height: 50px; padding-right:5px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script> <div id="app"> <input type="file" @change="onFileChange" /><br> <input type="file" @change="onFileChange2" /><br> <input type="file" @change="onFileChange3" /> <div id="preview"> <img v-if="url":src="url" /><br><br> <img v-if="url2":src="url2" /><br><br> <img v-if="url3":src="url3" /> </div> </div>

You can use multiple in file input and then create array of images:您可以在文件输入中使用multiple ,然后创建图像数组:

 new Vue({ el: '#app', data: () => ({ url: [], }), methods: { onFileChange(e) { [...e.target.files].forEach(f => this.url.push(URL.createObjectURL(f))) }, } })
 body { background-color: #e2e2e2; } #app { padding: 20px; } #preview { display: flex; justify-content: center; align-items: center; } #preview img { max-width: 100%; max-height: 50px; padding-right:5px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script> <div id="app"> <input type="file" multiple @change="onFileChange" /> <div id="preview" v-for="(img, i) in url":key="i"> <img:src="img" /> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM