组件模板中定义的方法简单,不会触发。 单击上传按钮时,我希望触发uploadFiles方法,以便在用户提交表单之前上传图像。
我只是不明白为什么它不起作用。我也试过v-on:click =" uploadFiles"但仍然没有运气。
我正在使用Laravel btw。
HTML表单
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">Create a new project</div>
<div class="card-body">
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
<form method="post" action="/project/store">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" id="title">
</div>
<div class="form-group">
<label for="title">Subtitle</label>
<input type="text" class="form-control" name="subtitle" id="subtitle">
</div>
<div id="app">
<upload-project-image></upload-project-image>
</div>
<div class="form-group">
<label for="sel2">Mutiple select list (hold shift to select more than one):</label>
<select multiple class="form-control" id="categories" name="categories[]">
@foreach($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
@endforeach
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Description</label>
<textarea name="body" class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button class="btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
app.js
require('./bootstrap');
window.Vue = require('vue');
Vue.component('upload-project-image', require('./components/UploadImage.vue'));
const app = new Vue({
el: '#app'
});
组件
<template>
<div>
<div class="form-group">
<label for="sel2">Select Project Images</label>
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" name="files[]"
id="files" multiple>
<label class="custom-file-label" for="inputGroupFile02">{{numberOfFiles}}</label>
</div>
<div class="input-group-append">
<button class="btn btn-outline-secondary" @click="uploadFiles" type="button">Upload</button>
</div>
</div>
</div>
</div>
</template>
<script>
export default{
data(){
return{
files:{},
numberOfFiles: 0
}
},
methods:{
uploadFiles(){
console.log("Nothing gets printed to the console");
},
uploadSongs(){
const fileInput = document.querySelector( '#files' );
const files = fileInput.files;
this.numberOfFiles = files.length;
for(let i=0; i < files.length; i++){
let formData = new FormData();
formData.append('files[]', files[i]);
axios.post( '/upload', formData ).then( ( response ) => {
console.log(response);
})
}
}
}
}
</script>
答案 0 :(得分:0)
这是因为形式。在表单中,任何单击事件/按钮都将被视为提交(页面重新加载),除非指定。要阻止它提交,您可以执行以下操作