La 단일 페이지 애플리케이션 DB에서 기본 작업의 주기를 완료할 수 있습니다: 생성, 읽기, 업데이트 및 삭제 Vue.js , Vue 라우터 및 라 라벨 프레임 워크 .
요즘 가장 인기 있는 JS 프레임워크는 Angular JS와 Vue JS입니다. Angular JS 및 Vue JS는 매우 사용자 친화적이고 가장 인기 있는 JS 프레임워크입니다. 페이지를 새로 고치지 않고 전체 프로젝트 또는 애플리케이션을 관리하고 강력한 jquery 유효성 검사를 제공합니다.
Vue는 Laravel과 함께 사전 패키지로 제공됩니다. 라라벨 믹스 , 에 기반한 훌륭한 저작 도구 웹팩 ) 개발자가 트랜스파일러, 코드 패키지, 소스 맵 또는 최신 프런트엔드 개발의 기타 "더러운" 측면에 대해 걱정하지 않고 복잡한 단일 페이지 애플리케이션 구축을 시작할 수 있습니다.
PHP 7.4
라 라벨 8.x
MySQL의
먼저 터미널을 열고 다음 명령을 실행하여 새 laravel 프로젝트를 만듭니다.
composer create-project --prefer-dist laravel/laravel crud-spa
또는 Laravel 설치 프로그램을 작성기 전역 종속성으로 설치한 경우:
laravel new crud-spa
설치 후 프로젝트 루트 디렉터리로 이동하여 .env 파일을 열고 다음과 같이 데이터베이스 세부 정보를 설정합니다.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=<DATABASE NAME>
DB_USERNAME=<DATABASE USERNAME>
DB_PASSWORD=<DATABASE PASSWORD>
다음 명령을 실행하여 프런트 엔드 종속성을 설치합니다.
npm install
그 후 설치 vue , 뷰 라우터 e vue-axios . Vue-axios는 Laravel 백엔드 API를 호출하는 데 사용됩니다. 터미널에서 다음 명령을 실행합니다.
npm install vue vue-router vue-axios --save
범주 템플릿, 마이그레이션 및 컨트롤러를 만듭니다. 이를 위해 다음 명령을 실행합니다.
php artisan make:model Category -mcr
-mcr 이 항목에서는 단일 명령 합성을 사용하여 모델, 마이그레이션 및 컨트롤러를 생성합니다.
이제 카테고리 마이그레이션 파일을 엽니다. 데이터베이스 / 마이그레이션 코드를 함수로 바꿉니다. 위로() :
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
다음 명령을 사용하여 데이터베이스를 마이그레이션합니다.
php artisan migrate
이제 다음에서 Category.php 템플릿을 엽니다.app/Models
파일의 코드를 편집합니다. model
카테고리.php :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model {
use HasFactory;
protected $fillable = ['title','description'];
}
?>
그 후, 열기 카테고리 컨트롤러.php 다음과 같이 index, store, update 및 delete 메서드에 코드를 추가합니다.
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$categories = Category::all(['id','title','description']);
return response()->json($categories);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$category = Category::create($request->post());
return response()->json([
'message'=>'Category Created Successfully!!',
'category'=>$category
]);
}
/**
* Display the specified resource.
*
* @param \App\Models\Category $category
* @return \Illuminate\Http\Response
*/
public function show(Category $category)
{
return response()->json($category);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Category $category
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Category $category)
{
$category->fill($request->post())->save();
return response()->json([
'message'=>'Category Updated Successfully!!',
'category'=>$category
]);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Category $category
* @return \Illuminate\Http\Response
*/
public function destroy(Category $category)
{
$category->delete();
return response()->json([
'message'=>'Category Deleted Successfully!!'
]);
}
}
지금 defi끝내다 routes
파일에서 웹.php e API.php . 폴더로 이동 routes
web.php 및 api.php 파일을 열고 다음을 업데이트합니다. routes
:
routes/web.php
<?php
Route::get('{any}', function () {
return view('app');
})->where('any', '.*');
routes/api.php
<?php
Route::resource('category',App\Http\Controllers\CategoryController::class)->only(['index','store','show','update','destroy']);
이 단계에서 디렉토리로 이동합니다. 자원/보기, 파일 생성 app.blade.php 에 다음 코드를 추가하십시오. app.blade.php:
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" value="{{ csrf_token() }}"/>
<title>Laravel Vue CRUD App</title>
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet" type="text/css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link href="{{ mix('css/app.css') }}" type="text/css" rel="stylesheet"/>
</head>
<body>
<div id="app">
</div>
<script src="{{ mix('js/app.js') }}" type="text/javascript"></script>
</body>
</html>
이 단계에서 폴더로 이동합니다. resource/js
, 폴더 생성 components
다음과 같이 파일을 만듭니다.
View app
Welcome.vue
Category/List.vue
Category/Add.vue
Category/Edit.vue
앱뷰 Vue 앱의 기본 파일입니다. Defi우리는 끝낼 것이다 라우터 보기 그 파일에서. 모든 경로가 파일에 나타납니다. 앱뷰 .
파일 열기 Welcome.vue
해당 파일에서 다음 코드를 업데이트합니다.
<template>
<div class="container mt-5">
<div class="col-12 text-center">
<h1>Laravel Vuejs CRUD</h1>
</div>
</div>
</template>
App.vue 파일을 열고 다음과 같이 코드를 업데이트합니다.
<template>
<main>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<router-link to="/" class="navbar-brand" href="#">Laravel Vue Crud App</router-link>
<div class="collapse navbar-collapse">
<div class="navbar-nav">
<router-link exact-active-class="active" to="/" class="nav-item nav-link">Home</router-link>
<router-link exact-active-class="active" to="/category" class="nav-item nav-link">Category</router-link>
</div>
</div>
</div>
</nav>
<div class="container mt-5">
<router-view></router-view>
</div>
</main>
</template>
<script>
export default {}
</script>
그런 다음 열기 resource / js / components / category / List.vue
파일에 다음 코드를 추가합니다.
<template>
<div class="row">
<div class="col-12 mb-2 text-end">
<router-link :to='{name:"categoryAdd"}' class="btn btn-primary">Create</router-link>
</div>
<div class="col-12">
<div class="card">
<div class="card-header">
<h4>Category</h4>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody v-if="categories.length > 0">
<tr v-for="(category,key) in categories" :key="key">
<td>{{ category.id }}</td>
<td>{{ category.title }}</td>
<td>{{ category.description }}</td>
<td>
<router-link :to='{name:"categoryEdit",params:{id:category.id}}' class="btn btn-success">Edit</router-link>
<button type="button" @click="deleteCategory(category.id)" class="btn btn-danger">Delete</button>
</td>
</tr>
</tbody>
<tbody v-else>
<tr>
<td colspan="4" align="center">No Categories Found.</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name:"categories",
data(){
return {
categories:[]
}
},
mounted(){
this.getCategories()
},
methods:{
async getCategories(){
await this.axios.get('/api/category').then(response=>{
this.categories = response.data
}).catch(error=>{
console.log(error)
this.categories = []
})
},
deleteCategory(id){
if(confirm("Are you sure to delete this category ?")){
this.axios.delete(`/api/category/${id}`).then(response=>{
this.getCategories()
}).catch(error=>{
console.log(error)
})
}
}
}
}
</script>
그 후, 열기 resource /js/components/category/Add.vue
파일에서 다음 코드를 업데이트합니다.
<template>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h4>Add Category</h4>
</div>
<div class="card-body">
<form @submit.prevent="create">
<div class="row">
<div class="col-12 mb-2">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" v-model="category.title">
</div>
</div>
<div class="col-12 mb-2">
<div class="form-group">
<label>Description</label>
<input type="text" class="form-control" v-model="category.description">
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name:"add-category",
data(){
return {
category:{
title:"",
description:""
}
}
},
methods:{
async create(){
await this.axios.post('/api/category',this.category).then(response=>{
this.$router.push({name:"categoryList"})
}).catch(error=>{
console.log(error)
})
}
}
}
</script>
그 후, 열기 resource /js/components/category/Edit.vue
파일에서 다음 코드를 업데이트합니다.
<template>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h4>Update Category</h4>
</div>
<div class="card-body">
<form @submit.prevent="update">
<div class="row">
<div class="col-12 mb-2">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" v-model="category.title">
</div>
</div>
<div class="col-12 mb-2">
<div class="form-group">
<label>Description</label>
<input type="text" class="form-control" v-model="category.description">
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name:"update-category",
data(){
return {
category:{
title:"",
description:"",
_method:"patch"
}
}
},
mounted(){
this.showCategory()
},
methods:{
async showCategory(){
await this.axios.get(`/api/category/${this.$route.params.id}`).then(response=>{
const { title, description } = response.data
this.category.title = title
this.category.description = description
}).catch(error=>{
console.log(error)
})
},
async update(){
await this.axios.post(`/api/category/${this.$route.params.id}`,this.category).then(response=>{
this.$router.push({name:"categoryList"})
}).catch(error=>{
console.log(error)
})
}
}
}
</script>
지금, 당신은 defi끝내다 Vue routes
, 이렇게 하려면 폴더로 이동합니다. resource / js
, 파일 생성 route.js
파일에서 다음 코드를 업데이트합니다.
const Welcome = () => import('./components/Welcome.vue' /* webpackChunkName: "resource/js/components/welcome" */)
const CategoryList = () => import('./components/category/List.vue' /* webpackChunkName: "resource/js/components/category/list" */)
const CategoryCreate = () => import('./components/category/Add.vue' /* webpackChunkName: "resource/js/components/category/add" */)
const CategoryEdit = () => import('./components/category/Edit.vue' /* webpackChunkName: "resource/js/components/category/edit" */)
export const routes = [
{
name: 'home',
path: '/',
component: Welcome
},
{
name: 'categoryList',
path: '/category',
component: CategoryList
},
{
name: 'categoryEdit',
path: '/category/:id/edit',
component: CategoryEdit
},
{
name: 'categoryAdd',
path: '/category/add',
component: CategoryCreate
}
]
여기서 우리는 구성 요소를 사용했습니다. 느린 로딩. 뷰 JS 방식으로 구성 요소의 로드를 관리합니다. lazy
따라서 DOM에서는 경로를 통해 필요할 때만 구성 요소를 로드할 수 있습니다.
이제 모든 경로, vue-axios 및 기타 종속성을 추가해야 합니다.
resource / js / app.js
require('./bootstrap');
import vue from 'vue'
window.Vue = vue;
import App from './components/App.vue';
import VueRouter from 'vue-router';
import VueAxios from 'vue-axios';
import axios from 'axios';
import {routes} from './routes';
Vue.use(VueRouter);
Vue.use(VueAxios, axios);
const router = new VueRouter({
mode: 'history',
routes: routes
});
const app = new Vue({
el: '#app',
router: router,
render: h => h(App),
});
webpack.mix.js
const mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel applications. By default, we are compiling the CSS
| file for the application as well as bundling up all the JS files.
|
*/
mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
//
]).vue();
터미널을 열고 다음 명령을 실행합니다.
npm run watch
php artisan serve
APRI 로컬 호스트 : 8000 브라우저에서.
BlogInnovazione.it
색칠을 통해 소근육 운동 능력을 키우면 아이들이 글쓰기와 같은 보다 복잡한 기술을 준비할 수 있습니다. 색칠하다…
지난 월요일, Financial Times는 OpenAI와의 계약을 발표했습니다. FT는 세계적 수준의 저널리즘에 라이선스를 부여합니다…
수백만 명의 사람들이 스트리밍 서비스 비용을 지불하고 월간 구독료를 지불합니다. 당신은…