Skip to content

Instantly share code, notes, and snippets.

@abler98
Last active October 11, 2016 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abler98/d8e221edf8638700a5c1dcc09d5891b7 to your computer and use it in GitHub Desktop.
Save abler98/d8e221edf8638700a5c1dcc09d5891b7 to your computer and use it in GitHub Desktop.
Vue Component
<template>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
Загрузить фотографию
</div>
<div class="panel-body" v-notifications>
<form :action="source" @submit.prevent="store" role="form">
<div v-if="photo" class="form-group">
<img :src="photo" class="img-thumbnail" alt="Фотография для загрузки">
</div>
<div :class="[{ 'has-error': validator.errors.has('photo') }, 'form-group']">
<label class="control-label" for="photo">Фотография</label>
<input @change.prevent="onFileChange" accept="image/*" type="file" id="photo" class="form-control">
</div>
<div :class="[{ 'has-error': validator.errors.has('description') }, 'form-group']">
<label class="control-label" for="description">Описание</label>
<textarea v-model="form.description" id="description" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-primary">Добавить</button>
</form>
</div>
</div>
</div>
</div>
</template>
<style>
.img-thumbnail {
max-width: 100%;
}
</style>
<script>
export default {
props: {
source: String,
},
data () {
return {
form: {
description: '',
photo: null,
},
validator: {
// For reactivity
},
photo: null,
}
},
created () {
this.validator = require('../../validator')(this);
},
methods: {
store () {
this.$http.post(this.source, this.getStoreForm())
.then(this.success, this.error);
},
getStoreForm () {
var form = new FormData();
form.append('photo', this.form.photo);
form.append('description', this.form.description);
return form;
},
onFileChange (e) {
if (e.target && e.target.files) {
if (e.target.files.length > 0) {
this.selectImage(e.target.files[0]);
}
}
},
selectImage (file) {
if (file.type.match(/^image\/.*$/g)) {
var reader = new FileReader();
reader.addEventListener('load', function (e) {
this.photo = e.target.result;
this.form.photo = file;
}.bind(this));
reader.readAsDataURL(file);
}
},
success (response) {
this.$flash('Фотография успешно добавлена');
bus.$emit('added-album-photo', response.body);
this.clearForm();
},
error (response) {
if (response.status == 422) {
this.$flash('Ошибка валидации данных', 'danger');
this.validator.handle(response.body);
return;
}
this.$flash('Произошла ошибка сервера', 'danger');
},
clearForm () {
this.form.description = '';
this.form.photo = null;
this.photo = null;
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment