Home > Net >  Vuejs bind images based on selection
Vuejs bind images based on selection

Time:09-17

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. 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

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>

CodePudding user response:

You can use multiple="multiple" in file input and then create array of images:

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="multiple" @change="onFileChange" /><br>
  <div id="preview" v-for="(img, i) in url" :key="i">
    <img :src="img" />
  </div>
</div>

  • Related