javascript - 为什么在 vuejs 中将数据插入表时我的提交按钮不起作用
问题描述
我在brand.vue中制作了一个“添加新”按钮,单击该按钮后会出现一个模态,模态的Id是addNewBrandModal。他们我们可以找到一个创建按钮。那个按钮不起作用,照片没有上传,数据也没有插入数据库。我是新手。在运行这个网站时,我得到了 100 多个没有图像但他们没有数据库和文件夹中的数据。
This is my brand.vue component.
<template>
<div class="container">
<div class="row pt-5">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Brand</h3>
<div class="card-tools">
<button class="btn btn-success" type="button" @click="createModal">
Add New <i class="fas fa-image"></i>
</button>
</div>
</div>
<!-- /.card-header -->
<div class="card-body p-4" v-if="brands.length > 0">
<div class="row">
<p>HELLO</p>
<div class="col-md-4" v-for="brand in brands" :key="brand.id"
v-bind:class="{ 'mb-4': brands.length >= 3}"
>
<div class="gallery-area">
<div class="img-area">
<img :src="getImage(brand.image)" width="90px" height="60px">
<div class="icon">
<ul class="list-inline d-flex flex-inline">
<li>
<a href="#" title="Edit Gallery" @click="editModal(brand)">
<i class="fa fa-edit"></i>
</a>
</li>
<li>
<a href="#" title="Delete Gallery" class="btn-delete-m"
@click="deleteBrand(brand.id)">
<i class="fa fa-trash"></i>
</a>
</li>
</ul>
<span class="title">{{brand.title}}</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div v-else class="m-5">
<p class="title text-center"><span style="color:red">*</span>Size of image should be less than 2 mb</p>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</div>
<!-- row end -->
<!-- Modal -->
<div class="modal fade" id="addNewBrandModal" tabindex="-1" role="dialog" aria-labelledby="addNewBrandModal" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addNewBrandModal" v-if="!editmode">New Brand</h5>
<h5 class="modal-title" id="addNewBrandModal" v-else>Update Brand Info</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form @submit.prevent="editmode ? updateBrand() : createBrand()">
<div class="modal-body">
<div class="form-group">
<input v-model="form.title" type="text" name="title"
class="form-control" :class="{ 'is-invalid': form.errors.has('title') }"placeholder="Brand Title">
<has-error :form="form" field="title"></has-error>
</div>
<div class="form-group">
<label v-if="editmode">New Image</label>
<div class="input-group">
<div class="custom-file">
<input type="file" @change="uploadImage" name="image" class="custom-file-input" :class="{ 'is-invalid': form.errors.has('image') }" >
<has-error :form="form" field="image"></has-error>
<label class="custom-file-label" for="exampleInputFile">Choose Feature Image</label>
</div>
<div class="input-group-append">
<span class="input-group-text" id="">Upload</span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" v-if="editmode">Update</button>
<button type="submit" class="btn btn-primary" v-else>Create</button>
</div>
</form>
</div>
</div>
</div>
<!-- <!– modal end –>-->
</div>
</template>
<script>
export default {
data(){
return{
brands:[],
editmode:false,
form: new Form({
id: '',
title: '',
image: ''
})
}
} ,
methods:{
// loadBrand(){
//
// axios.get('api/brand')
// .then( ({data}) => {
// this.brands = data;
// })
//
// },
//
// getImage(imagename){
//
// return "images/brand/" + imagename;
//
// },
uploadImage(e){
// console.log('file upload');
let file = e.target.files[0];
// console.log(file); // file info like name, size
let reader = new FileReader();
if(file['size'] < 2111775){
reader.onloadend = (file) => {
this.form.image = reader.result;
// console.log(reader.result);
}
reader.readAsDataURL(file);
}else{
swal({
type: 'error' ,
title: 'Oops!' ,
text: 'You are uploading a large file'
})
}
},
createBrand(){
// progressbar start
this.$Progress.start();
this.form.post('api/brand')
.then(() => {
// progressbar finish
this.$Progress.finish();
$("#addNewBrandModal").modal("hide");
// toast message is fired
Toast.fire({
type: 'success',
title: 'Brand Created successfully'
})
this.loadBrand();
})
.catch(()=>{
// progressbar fail
this.$Progress.fail()
})
},
// updateBrand(){
//
// // progressbar start
// this.$Progress.start()
//
// this.form.put("api/brand/"+this.form.id)
// .then(() => {
//
// // progressbar finish
// this.$Progress.finish()
//
// $("#addNewBrandModal").modal("hide");
//
// // toast message is fired
// Toast.fire({
// type: 'success',
// title: 'Brand Info Updated successfully'
// })
//
// this.loadBrand();
//
// })
// .catch(() => {
//
// // progressbar fail
// this.$Progress.fail()
//
// })
//
// },
//
// deleteBrand(id){
//
// Swal.fire({
// title: 'Are you sure?',
// text: "You won't be able to revert this!",
// type: 'warning',
// showCancelButton: true,
// confirmButtonColor: '#3085d6',
// cancelButtonColor: '#d33',
// confirmButtonText: 'Yes, delete it!'
// }).then((result) => {
//
// if (result.value) {
// // progressbar start
// this.$Progress.start()
//
// this.form.delete("api/brand/"+id)
// .then(() => {
//
// Swal.fire(
// 'Deleted!',
// 'Brand has been deleted.',
// 'success'
// )
//
// // progressbar finish
// this.$Progress.finish();
//
// this.loadBrand();
//
// })
// .catch(() => {
//
// // progressbar fail
// this.$Progress.fail();
//
// });
// }
// })
// // swal fire end
//
// },
//
createModal(){
this.editmode = false;
this.form.reset();
$("#addNewBrandModal").modal("show");
} ,
//
// editModal(team){
//
// this.editmode = true;
// $("#addNewBrandModal").modal("show");
// this.form.fill(team);
//
// }
} ,
created(){
this.loadBrand();
}
}
</script>
<style type="text/css" scoped>
.gallery-area:hover .icon{
cursor: pointer;
opacity: 1;
filter: alpha(opacity=100);
transform: rotateY(0deg) scale(1,1);
}
.img-area{
overflow:hidden;
position: relative;
}
.img-area img{
width: 100%;
min-height: 200px;
}
.img-area:hover img{
transform: scale(1.2);
}
.img-area img{
transition: all 0.4s ease 0s;
}
.img-area .icon{
background-color: #3490dc;
position: absolute;
text-align: center;
height: 100%;
width: 100%;
top: 0;
left: 0;
opacity: 0;
filter: alpha(opacity=0);
transition: all 0.5s ease-out 0s;
transform: rotateY(180deg) scale(0.5,0.5);
}
.img-area .icon ul{
text-align: center;
position: relative;
top: 50px;
left: 130px;
}
.img-area .icon ul li a{
border:1px solid #fff;
color:#fff;
display: block;
font-size: 20px;
height: 35px;
text-align: center;
width: 35px;
}
.img-area .icon ul li a:hover{
background-color: #fff;
color:#da1e40;
border:1px solid transparent;
}
.img-area .icon .title{
text-align: center;
position: relative;
top: 80px;
left: 8px;
color: #fff;
font-size: 18px;
}
</style>
这是路由文件夹中的 api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', 'API\UserController@AuthRouteAPI');
Route::get('/getDashboardData','API\DashboardController@index');
//user
Route::apiResource('user','API\UserController');
// slider
Route::apiResource('slider','API\SliderController');
Route::post('slider/sorting','API\SliderController@sortOrder');
// service
Route::apiResource('service','API\ServiceController');
Route::post('service/sorting','API\ServiceController@sortOrder');
// team
Route::apiResource('team','API\TeamController');
// gallery
Route::apiResource('gallery','API\GalleryController');
// brand
Route::apiResource('brand','API\BrandController');
// testimonial
Route::apiResource('testimonial','API\TestimonialController');
// contact
Route::get('contact','API\ContactController@index');
Route::delete('contact/{id}','API\ContactController@destroy');
// ------- routes for company info -----------------
Route::get('company/info','API\InfoController@getData');
Route::post('logo/upload','API\InfoController@logoUpload');
Route::post('about/info','API\InfoController@saveAboutCompanyInfo');
Route::post('about/message','API\InfoController@saveAboutCompanyMessage');
Route::post('basic/info','API\InfoController@saveCompanyBasicInfo');
Route::post('social/info','API\InfoController@saveCompanySocialInfo');
Route::post('project/info','API\InfoController@saveCompanyProjectInfo');
这是我在控制器中的 BrandController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Brand;
use App\BrandImage;
use File;
class BrandController extends Controller
{
protected $width = 1200;
protected $height = 800;
protected $path1 = "";
protected $path2 = "";
public function __construct()
{
$this->path1 = public_path('/images/brand/');
$this->path2 = public_path('/images/brand/small/');
if(!File::isDirectory($this->path1)){
File::makeDirectory($this->path1, 0777, true);
}
// smaller service images
if (!file_exists($this->path2)) {
mkdir($this->path2, $mode = 0777, true);
}
}
/*
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$rows = Brand::all();
return $rows;
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// return $request->all();
// validate with laravel in real time
$request->validate([
'title' => 'required|string|max:200' ,
'image' => 'required'
]);
// image is stored in public folder
if($request->image){
$image_name = time() . '.' . explode('/' , explode(':', substr($request->image, 0 , strpos($request->image, ';')))[1])[1];
\Image::make($request->image)->resize($this->width, $this->height)
->save($this->path1.$image_name);
\Image::make($request->image)->resize(480, 360)->save($this->path2.$image_name);
}
// new brand created
Brand::create([
'title' => $request->get('title'),
'image' => $image_name,
]);
return ["message" => "Success"];
}
// brand image is stored
public function imageStore(Request $request,$id)
{
return $request->all();
$request->validate([
'images' => 'required'
]);
// image is stored in public folder
if($request->images){
$image_name = time() . '.' . explode('/' , explode(':', substr($request->images, 0 , strpos($request->images, ';')))[1])[1];
$newpath = public_path('/images/brand/',$id,'/');
if(!File::isDirectory($newpath)){
File::makeDirectory($newpath, 0777, true);
}
\Image::make($request->images)->resize($this->width, $this->height)
->save(public_path('images/brand/',$id,'/').$image_name);
}
BrandImage::create([
'brand_id' => $id,
'image' => $image_name
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$brand = Brand::find($id);
// validate with laravel in real time
$request->validate([
'title' => 'required|string|max:200' ,
'image' => 'sometimes'
]);
// if new image is uploaded saved and old removed
if($request->image != $brand->image){
$image_name = time() . '.' . explode('/' , explode(':', substr($request->image, 0 , strpos($request->image, ';')))[1])[1];
\Image::make($request->image)->resize($this->width, $this->height)->save($this->path1.$image_name);
\Image::make($request->image)->resize(480, 360)->save($this->path2.$image_name);
// delete old image
if($brand->image){
// unlink($this->path1 . $brand->image);
$this->deleteImage($brand->image);
}
}
// update team info
$brand->update([
'title' => $request->get('title'),
'image' => isset($image_name) ? $image_name : $brand->image,
]);
// return $request->all();
return ["message" => "Updated"];
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$brand = Brand::find($id);
// call another method
if($brand->image){
$this->deleteImage($brand->image);
}
$brand->delete();
return ["message" => 'Success'];
}
protected function deleteImage($imagename)
{
if(file_exists($this->path1.$imagename)){
unlink($this->path1 . $imagename);
}
if(file_exists($this->path2.$imagename)){
unlink($this->path2 . $imagename);
}
}
}
解决方案
推荐阅读
- node.js - 如何在进行 ember 生产构建时隐藏 .hbs 和 .js 中的部分
- python - 如果我们有概率密度函数数据作为 x 和 y,则计算百分位数
- gcloud - gcloud pubsub 发布消息问题
- authentication - Azure IoT 中心身份验证
- android - Android Sharedpreferences 仅在应用重启后更新
- office-js - 有没有办法使用 OfficeJS 获取 ChartPoint 的数字格式?
- java - 强制杰克逊将 LocalDate 序列化为数组
- javascript - 放大/缩小按钮不适用于 react-pdf
- sql - 通过选择包含特定单词的行来确定百分比
- ios - iOS内存警告:如何“清理尽可能多的内存”?