i'm working on an laravel vuejs spa.
I try to update a post from the admin. I send the form datas on creating a new FromData who are sending with and axios request.
But the controller send me the error:
message: "The given data was invalid."
errors: {name: ["The name field is required."], description: ["The description field is required."]}
Here is the post/edit.vue
<template>
<div class="post-edit">
<form id="form" #submit.prevent="createPost">
<!-- Title -->
<div class="form-group">
<label for="title" class="form-label">Title</label>
<input id="title" v-model="post.title" :title="post.title" type="text"
name="title" class="form-control"
>
</div>
<!-- Category -->
<div class="form-group">
<label for="category" class="form-label">Category</label>
<select id="category" v-model="post.category" :value="post.category" :category="post.category"
name="category" class="form-control"
>
<option disabled :value="post.category">
Choisir une catégorie
</option>
<option v-for="(category) in categories" :key="category.id" :value="post.category">
{{ category.name }}
</option>
</select>
</div>
<div class="post-edit-image">
<img :src="path + post.image" alt="">
</div>
<!-- Image -->
<div class="form-group post-edit-select-image">
<label for="content" class="form-label">Image</label>
<input type="file" name="image" class="form-control" #change="selectedImage">
</div>
<!-- Content -->
<div class="form-group">
<label for="content" class="form-label">Content</label>
<editor
id="content"
v-model="post.content"
api-key="the-api-key"
:init="{
height: 500,
menubar: false,
plugins: [
'advlist autolink lists link image charmap print preview anchor',
'searchreplace visualblocks code fullscreen',
'insertdatetime media table paste code help wordcount'
],
toolbar:
'undo redo | formatselect | bold italic backcolor | \
alignleft aligncenter alignright alignjustify | \
bullist numlist outdent indent | removeformat | help'
}"
name="content"
:content="post.content"
/>
</div>
<!-- Submit Button -->
<button type="submit" class="btn btn-primary">
Sauvegarder
</button>
</form>
</div>
</template>
<script>
import axios from 'axios'
import { mapGetters } from 'vuex'
import Editor from '#tinymce/tinymce-vue'
export default {
middleware: 'auth',
components: {
'editor': Editor
},
props: ['id'],
data () {
return {
post: {
id: '',
user_id: '',
title: '',
category: '',
image: null,
content: ''
},
path: '/images/post/thumbnail/'
}
},
computed: {
...mapGetters({
user: 'auth/user',
categories: 'categories/categories'
})
},
beforeCreate () {
this.$store.dispatch('categories/fetchCategories')
},
created () {
this.getPostById(this.$route.params.id)
},
methods: {
selectedImage (event) {
this.post.image = event.target.files[0]
},
getPostById (id) {
axios.get('/api/posts/edit/' + id)
.then((response) => {
this.post.id = response.data.id
this.post.user_id = response.data.user_id
this.post.title = response.data.title
this.post.category = response.data.category
this.post.image = response.data.image
this.post.content = response.data.content
})
.catch((error) => {
console.log(error)
})
},
createPost (e) {
this.post.userId = this.user.id
let formData = new FormData(e.target)
let id = this.post.id
formData.append('title', this.post.title)
formData.append('category', this.post.category)
formData.append('image', this.post.image)
formData.append('content', this.post.content)
axios.patch('/api/posts/update/' + id, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then((response) => {
console.log(response)
this.$store.dispatch('posts/fetchPosts')
})
.catch((error) => {
console.log(error)
})
this.$router.push({ name: 'admin' })
}
}
}
</script>
And here the laravel controller PostController#update method
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(PostUpdateRequest $request, $id)
{
$post = Post::findOrFail($id);
$post->update($request->getValidRequest());
return response()->json($request, 200);
}
And the custom validator PostUpdateRequest.php
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => 'required|max:250|unique:posts,title',
'category' => 'required',
'image' => 'mimes:jpg,jpeg,png,bmp',
'content' => 'required'
];
}
public function getValidRequest()
{
$image = $this->file('image');
$slug = Str::slug($this->input('title'));
if (isset($image)) {
$imageExt = $image->getClientOriginalExtension();
$currentDate = Carbon::now()->toDateString();
$imageName = $slug . '-' . $currentDate . '-' . uniqid() . '.' . $imageExt;
if (!Storage::disk('public')->exists('post')) {
Storage::disk('public')->makeDirectory('post');
}
if (!Storage::disk('public')->exists('post/thumbnail')) {
Storage::disk('public')->makeDirectory('post/thumbnail');
}
$path = "images/";
$postImage = Image::make($image)->resize(null, 1060, function ($constraint){
$constraint->aspectRatio();
})->save(public_path($path).'post/'.$imageName);
$thumbnail = Image::make($image)->fit(550, 550)
->save(public_path($path).'post/thumbnail/'.$imageName);
}
return [
'user_id' => Auth::user()->getAuthIdentifier(),
'category_id' => $this->input('category'),
'title' => $this->input('title'),
'slug' => $slug,
'content' => $this->input('content'),
'image' => $imageName,
'is_published' => $this->input('is_published') ?? false,
];
}
The api route in laravel
Route::patch('/update/{id}', 'Backend\PostController#update');
I use practically the same things to store a post, and it work's fine, the only difference is here i pass an id for the post to update and i not use the post method but patch for axios and the route (and i try with put, it's the same error).
thank's for your time !
append '_method' field with value 'PATCH' to formData
formData.append('_method', 'PATCH')
and send axios request post request to update data
axios.post('/api/posts/update/' + id, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
Related
I have a form that and I want it to have a CRUD function, I have made the function for the text, but I have no idea how to do CRUD with images,
Here is my code :
Model
protected $fillable= [
'nama',
'alamat',
'nomor',
'email',
];
Controller :
public function index()
{
return Form::all();
}
public function store(Request $request)
{
$data = $request->all();
$response = Form::create($data);
return response()->json([
'status' => 'success',
'data' => $response
], 200);
}
The Form :
<Form #submit="saveData()">
<div class="form-row form-section" id="formParent">
<div class="col-12 mb-3">
<Field name="nama" type="text" class="form-control1" v-model="form.nama" placeholder=" Nama Lengkap" :rules="isRequired" />
<br>
<ErrorMessage name="nama" />
<br>
<Field name="alamat" type="text" class="form-control2" v-model="form.alamat" placeholder=" Alamat" :rules="isRequired" />
<br>
<ErrorMessage name="alamat" />
<br>
<Field name="nomor" type="text" class="form-control3" v-model="form.nomor" placeholder=" Nomor Telfon" :rules="isRequired" />
<br>
<ErrorMessage name="nomor" />
<br>
<Field name="nomor" type="file" class="form-control3" v-model="form.nomor" placeholder=" Nomor Telfon" :rules="isRequired" />
<Field name="email" type="text" class="form-control4" v-model="form.email" placeholder=" Email" :rules="validateEmail" />
<br>
<ErrorMessage name="email" />
</div>
<button class="btnSubmit" type="submit">
Gabung Mitra
</button>
</div>
</Form>
Script :
<script>
import axios from 'axios';
import { Form, Field, ErrorMessage} from 'vee-validate';
export default {
components: {
Form,
Field,
ErrorMessage
},
data() {
return {
form: {
nama: '',
alamat: '',
nomor: '',
email: '',
},
};
},
methods: {
isRequired(value){
if (value && value.trim()){
return true;
}
return 'This is required';
},
validateEmail(value) {
// if the field is empty
if (!value) {
return 'This field is required';
}
// if the field is not a valid email
const regex = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (!regex.test(value)) {
return 'This field must be a valid email';
}
// All is good
return true;
},
saveData(){
axios.post('/form/submit', this.form).then(
response => {
console.log(response);
this.$toast.success(`Data berhasil dikirim`,{
position: "bottom",
});
}
). catch(error => {
console.log('error');
this.$toast.error(`Terjadi kegagalan`,{
position: "bottom",
});
})
}
}
};
</script>
What should I do so that the user can upload an image to the form and save it to the database. I tried to change the field type to file, but I have no idea how the function works in the controller.
For storing images with Form you need to add few lines inside contoller for handling and storing image and also you need to add enctype inside form submit.
First you need to change :
<Form #submit="saveData()" enctype="multipart/form-data">
Now you need to change image input field :
<Field name="image" type="file" class="form-control3" v-model="form.image" :rules="isRequired" />
And inside the controller you need to change code for request :
public function store(Request $request)
{
$data = $request->all();
if ($request->hasFile('image')) {
$image = $request->file('image');
$path = $image->store('public/images');
$data['image'] = $path;
}
$response = Form::create($data);
return response()->json([
'status' => 'success',
'data' => $response
], 200);
}
And finally in your model :
protected $fillable = [
'nama',
'alamat',
'nomor',
'email',
'image',
];
I'm working on a laravel 9 project that uses vue 3. For each form input has been made field components.Everything works fine except registration checkbox (Accept terms). If the checkbox is used normally in vue, it works fine. as soon as a component is made of it, it no longer works. By clicking the chackbox on and off I get the message that the accept terms is required!
I hope you can help me with this
-Vue Registration Form componetnt
<template>
<form class="text-left" method="post" #submit.prevent="submit()">
<div class="alert alert-success mb-1" v-if="success" v-html="successMessage"></div>
<div class="alert alert-danger mb-1" v-if="errors.message" v-html="errors.message"></div>
<InputFieldWithoutIcon ref="email" type="email" name="email" label="E-mail" :errors="errors" #update:field="fields.email=$event"/>
<InputFieldWithoutIcon ref="password" type="password" name="password" label="Password" :errors="errors" #update:field="fields.password=$event"/>
<InputFieldWithoutIcon ref="password_confirmation" type="password" name="password_confirmation" label="Password Confirmation" :errors="errors" #update:field="fields.password_confirmation=$event"/>
<Checkbox :text="newsletter_text" name="newsletter" type="checkbox" :errors="errors" #update:field="fields.newsletter=$event"/>
<Checkbox :text="policy_text" name="policy_accepted" type="checkbox" :errors="errors" #update:field="fields.policy_accepted=$event"/>
<SubmitButtonWithoutIcon name="create account" type="submit" custom_btn_class="btn-block btn-primary" custom_div_class=""/>
</form>
</template>
<script>
import InputFieldWithoutIcon from "../components/InputFieldWithoutIcon";
import SubmitButtonWithoutIcon from "../components/SubmitButtonWithoutIcon";
import Checkbox from "../components/Checkbox";
export default {
name: "RegistrationUser",
components: {
InputFieldWithoutIcon,
SubmitButtonWithoutIcon,
Checkbox
},
data() {
return {
fields: {
email: '',
password: '',
password_confirmation: '',
policy_accepted: '',
newsletter: '',
},
errors: {},
success: false,
successMessage: '',
newsletter_text: 'I want to receive newsletters',
policy_text: 'I accept <a class="text-bold text-underline" href="" target="_blank" title="privacy policy">the policy</a>',
}
},
methods: {
submit() {
axios.post('/api/registration', this.fields)
.then(response => {
if (response.status === 200) {
this.$refs.email.value = null;
this.$refs.password.value = null;
this.$refs.password_confirmation.value = null;
this.fields = {
email: '',
password: '',
password_confirmation: '',
policy_accepted: '',
newsletter: '',
};
this.errors = {};
this.success = true;
this.successMessage = response.data.message;
}
}).catch(errors => {
if (errors.response.status === 422 || errors.response.status === 401) {
this.errors = errors.response.data.errors;
}
});
}
}
}
</script>
-Vue Checkbox component
<template>
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
:id="name"
:name="name"
:type="type"
v-model="value"
#input="updateField()"
>
<label class="custom-control-label" :for="name">
{{ text }}
</label>
<div class="invalid-feedback" v-text="errorMessage()"></div>
</div>
</template>
<script>
export default {
name: "Checkbox",
props: [
'name',
'type',
'text',
'errors'
],
data: function () {
return {
value: false
}
},
computed: {
hasError: function () {
return this.errors && this.errors[this.name] && this.errors[this.name].length > 0;
}
},
methods: {
updateField: function () {
this.clearErrors(this.name);
this.$emit('update:field', this.value)
},
errorMessage: function () {
if (this.errors && this.errors[this.name]) {
return this.errors[this.name][0];
}
},
clearErrors: function () {
if (this.hasError) {
this.errors[this.name] = null;
}
}
}
}
</script>
-Laravel Registration request
public function rules(): array
{
return [
'email' => 'required|email|unique:users',
'password' => 'required|confirmed|min:8',
'newsletter' => 'nullable|boolean',
'policy_accepted' => 'accepted'
];
}
I've found the solution.
In the checkbox template instead of using #input="updateField()" I replaced that with #change="updateField()"
That's all!
I tried to solve this Laravel - Vue input problem and I can't find the solution. I follow my teacher's tutorial and it's work. But when I tried mine and open the console, I found it show error with message :
`Access to XMLHttpRequest at 'http://localhost/lat_laravel-vue1/public/api/siswa/tambahsiswa' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.`
and when I click the Laravel's link, it show me an error message
"The GET method is not supported for this route. Supported methods: POST.".
I use Laravel 5.8 version.
https://i.stack.imgur.com/0z6C2.png
Laravel Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\siswaModel;
use Illuminate\Support\Facades\Validator;
header('Access-Control-Allow-Origin: *');
class siswaController extends Controller
{
public function simpan(Request $req)
{
$validator = Validator::make($req->all(), [
'nama_siswa' => 'required',
'tanggal_lahir' => 'required',
'gender' => 'required',
'id_kelas' => 'required'
]);
if ($validator->fails()) {
return Response()->json($validator->errors());
}
$simpan = siswaModel::create([
'nama_siswa' => $req->nama_siswa,
'tanggal_lahir' => $req->tanggal_lahir,
'gender' => $req->gender,
'id_kelas' => $req->id_kelas,
'alamat' => $req->alamat
]);
if ($simpan) {
$data['status'] = true;
$data['message'] = "Sukses Menambahkan Siswa";
} else {
$data['status'] = false;
$data['message'] = "Gagal Menambahkan Siswa";
}
return $data;
}
}
Routes
Route::post('/tambahsiswa', 'siswaController#simpan');
Vue file
<div class="container">
Nama Siswa
<input type="text" name="nama_siswa" v-model="nama_siswa" class="form-control">
<br>
Tanggal Lahir
<input type="date" name="tanggal_lahir" v-model="tanggal_lahir" class="form-control">
<br>
Gender
<select name="gender" v-model="gender" class="form-control">
<option></option>
<option v-for="gender in listgender" :key="gender.key" value="{{gender.key}}">{{gender.val}}</option>
</select>
<br>
Alamat
<textarea rows="4" class="form-control" v-model="alamat" name="alamat"></textarea>
<br>
Kelas
<select name="kelas" v-model="kelas" class="form-control">
<option></option>
<option v-for="kelas in listkelas" :key="kelas.id" value="{{kelas.id}}">{{kelas.nama_kelas}}</option>
</select>
<br>
<button class="btn btn-primary" #click="simpansiswa()">Simpan</button>
</div>
</template>
<script>
export default {
name: "Tambahsiswa",
data() {
return {
'listgender': [
{ key: 'L', val: 'Laki-laki' },
{ key: 'P', val: 'Perempuan' }
],
listkelas: [],
nama_siswa: '',
tanggal_lahir: '',
gender: '',
alamat: '',
kelas: '',
}
},
methods: {
getkelas:function() {
this.axios.get('http://localhost/lat_laravel-vue1/public/api/getkelas').then((result) => {
this.listkelas = result.data
})
},
simpansiswa:function() {
var datasiswa = {
nama_siswa: this.nama_siswa,
tanggal_lahir: this.tanggal_lahir,
gender: this.gender,
alamat: this.alamat,
id_kelas: this.kelas
}
this.axios.post('http://localhost/lat_laravel-vue1/public/api/siswa/tambahsiswa', datasiswa).then((result) => {
console.log(result)
})
}
},
mounted(){
this.getkelas();
}
}
</script>```
Are your Laravel and Vue is in one project ?
No : Laravel 5.8 default has no CORS. Can you check installed any package to config CORS ?
Yes : Try using Axios with CDN instead of javascript package and post data again.
https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js
Goodtime
I write this code but when i send for database only submit one query "sad" !
çi use
$request->has('happy') or ... no working
Can anyone help me?
for sample
**$request->has('happy') ** submit 'happy' or **$request->has('love') ** submit 'love'
I'm tired of searching
thanks to stackoverflow and members
<form method="post">
{{csrf_field()}}
<button type="submit" value="happy" id="happy" class="border-0 btn-submit">
<img src="/assets/images/reactions/happy.png" />
</button>
<button type="submit" value="angry" id="angry" class="border-0 btn-submit">
<img src="/assets/images/reactions/angry.png" />
</button>
<button type="submit" value="ill" id="ill" class="border-0 btn-submit">
<img src="/assets/images/reactions/ill.png" />
</button>
<button type="submit" value="love" id="love" class="border-0 btn-submit">
<img src="/assets/images/reactions/in-love.png" />
</button>
<button type="submit" value="quiet" id="quiet" class="border-0 btn-submit">
<img src="/assets/images/reactions/quiet.png" />
</button>
<button type="submit" value="sad" id="sad" class="border-0 btn-submit">
<img src="/assets/images/reactions/sad.png" />
</button>
<!-- <input type="text" name="studentName" id="studentName" class="form-control" placeholder="please type in your name"> -->
<input type="hidden" value="{{$article->id}}" id="post_id">
<input type="hidden" name="_token" value="{{csrf_token()}}">
</form>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit").click(function(e) {
e.preventDefault();
var post_id = $("#post_id").val();
var sad = $("#sad").val();
var quiet = $("#quiet").val();
var love = $("#love").val();
var ill = $("#ill").val();
var angry = $("#angry").val();
var happy = $("#happy").val();
$.ajax({
type: 'POST',
url: "{{ route('ajaxRequest.post') }}",
data: {
post_id: post_id,
sad: sad,
quiet: quiet,
love: love,
ill: ill,
angry: angry,
happy: happy
},
success: function(data) {
alert(data.success);
}
});
});
</script>
</div>
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Reaction;
use Illuminate\Support\Facades\Auth;
class AjaxController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function ajaxRequest()
{
return view('ajaxRequest');
}
/**
* Create a new controller instance.
*
* #return void
*/
public function ajaxRequestPost(Request $request, Reaction $reaction)
{
$input = $request->all();
\Log::info($input);
if ($request->ajax()) {
if (!Auth::user()) { // Check is user logged in
$must_login = "you must login";
return response()->json(['success' => $must_login]);
} else {
$date = date('Y-m-d');
$user_id = Auth::user()->id;
$output = "Your reaction Submited";
$post_id = $request->input('post_id');
// Checker
$checker = Reaction::select('*')->where([
['post_id', '=', $post_id],
['user_id', '=', $user_id],
['date', '=', $date]
])->first();
if ($checker == null) {
if ($request->has('sad') == true) {
Reaction::create([
'user_id' => $user_id,
'post_id' => $post_id,
'reaction' => 'sad',
'date' => $date,
]);
} elseif ($request->has('love')) {
Reaction::create([
'user_id' => $user_id,
'post_id' => $post_id,
'reaction' => 'love',
'date' => $date,
]);
} else {
echo "fuck";
}
return response()->json(['success' => $output]);
} else {
return response()->json(['success' => 'You Befor Submited Your Rection']);
}
}
}
}
}
This should work:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("form").on('submit', function(e) {
e.preventDefault();
var post_id = $("#post_id").val();
var reaction = $(".btn-submit").val();
$.ajax({
type: 'POST',
url: "{{ route('ajaxRequest.post') }}",
data: { post_id, reaction },
success: function(data) {
alert(data);
}
});
});
public function ajaxRequestPost(Request $request)
{
$data = $request->all();
return response()->json($data);
}
I have tried to upload a file using vue.js as front end technology and laravel in the back end. I have tried to pass the file object using formData javascript object but the server responds as the value is not passed.
I have tried to log the file using console.log and it appropriately displays the data.
Consider that I have discarded some field names.
Template Code
<template>
<b-container>
<div align="center">
<b-card class="mt-4 mb-4 col-md-8" align="left" style="padding: 0 0;">
<card-header slot="header" />
<b-form>
<div class="row">
<div class="col-6 col-md-6">
<b-button
type="submit"
variant="success"
class="float-right col-md-5"
v-if="!update"
#click="save"
squared
>
<i class="fas fa-save"></i>
Save
</b-button>
</div>
</div>
<hr style="margin-top: 10px;" />
<b-form-group
label-cols="12"
label-cols-lg="3"
label-for="input-2"
label="Remark: "
label-align-sm="right"
label-align="left"
>
<b-form-textarea
id="textarea"
v-model="record.remark"
rows="2"
max-rows="3"
></b-form-textarea>
</b-form-group>
<b-form-group
label-cols="12"
label-cols-lg="3"
label-for="input-2"
label="Remark: "
label-align-sm="right"
label-align="left"
>
<b-form-file
v-model="record.attachement"
:state="Boolean(record.attachement)"
placeholder="Choose a file..."
drop-placeholder="Drop file here..."
></b-form-file>
</b-form-group>
</b-form>
<status-message ref="alert" />
</b-card>
</div>
</b-container>
</template>
Script Code
<script>
import { mapGetters, mapActions } from "vuex";
export default {
props: ["id", "user_id"],
data: () => ({
record: {
remark: "",
attachement: null
}
}),
methods: {
...mapActions([
"addBenefitRequest",
]),
save(evt) {
evt.preventDefault();
this.$validator.validate().then(valid => {
if (valid) {
const Attachement = new FormData();
Attachement.append("file", this.record.attachement);
var object = {
remark: this.remark
};
this.addBenefitRequest(object, Attachement);
}
});
},
},
computed: mapGetters([
"getStatusMessage",
"getBenefitRequest",
])
};
</script>
Store Code
async addBenefitRequest({ commit }, object, Attachement) {
try {
const response = await axios.post(
commonAPI.BENEFIT_BASE_URL + "/benefit-requests",
object,
Attachement,
{
headers: {
"Content-Type": "multipart/form-data"
}
}
);
commit("pushBenefitRequest", response.data);
commit("setStatusMessage", "Record has been added.");
} catch (error) {
return error
},
Controller Code
public function store(Request $request, Request $request2)
{
$this->validate($request, [
'employee_id' => 'required|string',
'requested_date' => 'required|date',
// 'benefit_type_id' => 'required|string|exists:benefit_types,id',
'reason' => 'required|string',
]);
$this->validate($request2, [
'attachement' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
// $success = BenefitRequest::exists($request->employee_id);
// if(!$success)
// return response()->json("Employee doesn't exist", 422);
$id = (string) Str::uuid();
if($request2->attachement)
{
$attachement = $request2->file('attachement')->store('Benefits');
$request->merge(['attachement' => $attachement]);
}
// $request->attachement = $request->file('attachement')->store('Benefits');
$request->merge(['id' => $id]);
BenefitRequest::create($request->all());
return response()->json('Saved', 201);
}
Route
$router->post('',
['uses' => 'BenefitRequestController#store',
'group'=>'Benefit requests',
'parameter'=>'employee_id, requested_date, requested_by, benefit_type_id, reason, remark, status',
'response'=>'<statusCode, statusMessage>'
]);
Here is an example. you can try it
index.vue
`<div id="app">
<div v-if="!image">
<h2>Select an image</h2>
<input type="file" #change="onFileChange">
</div>
<div v-else>
<img :src="image" />
<button #click="removeImage">Remove image</button>
</div>
</div>`
new Vue({
el: '#app',
data: {
image: ''
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
removeImage: function (e) {
this.image = '';
}
}
})