yuudhees/laravel-vue-controller

在 Vue 文件中访问 Laravel 控制器

1.5 2024-03-04 16:17 UTC

This package is auto-updated.

Last update: 2024-09-05 05:21:05 UTC


README

注意

欢迎使用 laravel-vue-controller ,请您仔细阅读以下文档

安装

Composer

 composer require yudhees/laravel-vue-controller

或者

首先通过 Composer 安装此包。编辑您项目的 composer.json 文件,添加 yudhees/laravel-vue-controller 依赖。

"require-dev": {
     "yudhees/laravel-vue-controller": "1.5"
}

然后,在终端中更新 Composer

composer update 

注意

如果使用 Laravel > 4,请跳过以下步骤,因为服务提供者是自动发现的,因此不需要注册此提供者

Laravel <= 4

完成此操作后,下一步是添加服务提供者。打开 config/app.php,并将新项目添加到 providers 数组中。

Yudhees\LaravelVueController\vuecontrollerserviceprovider::class

注意

服务提供者包含默认路由,请确保此路由未在任何路由文件中注册

Route::post('/vuecontroller',vuecontroller::class)->name('vuecontroller');

使用方法

注意

在这个例子中,我使用的是 Inertia.js

在您的 app.js 文件中简单添加以下内容

import {controller} from '../../vendor/yudhees/laravel-vue-controller/compostables/global.js'

app.js

//resources/js/app.js
  import './bootstrap'
  import { createApp, h } from 'vue'
  import { createInertiaApp } from '@inertiajs/vue3'
  import {controller} from '../../vendor/yudhees/laravel-vue-controller/compostables/global.js'
    createInertiaApp({
     resolve: name => {
     const pages = import.meta.glob('./Pages/**/*.vue', { eager: true })
      return pages[`./Pages/${name}.vue`]
     },
      setup({ el, App, props, plugin }) {
     const app= createApp({ render: () => h(App, props) });
     app.use(plugin);
     app.mount(el);
   },
  })

全局

将控制器函数注入 Vue 组件的两种方式

提供/注入

//resources/js/app.js
createInertiaApp({
   ..........
   app.provide('controller', controller) // register controller as a provide
})

或者

全局属性

//resources/js/app.js
    createInertiaApp({
     ..........
     app.config.globalProperties.controller = controller; // register controller as a  global
     })

控制器函数

控制器函数接受两个参数,第一个参数代表控制器路径 controller(controllerPath,functionname,params={})

注意

控制器默认前缀路径为 App\Http\Controller

示例

我使用以下命令创建了一个 UserController

  php artisan make:controller UserController

示例 UserController 如下所示

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Inertia\Inertia;

class UserController extends Controller
{
   public function users(){
       return response(['users'=> User::all()]); // get all users
   }
   public function userlist(){
       return Inertia::render('userslist'); //render user list table
   }
   public function status($userid){ // change the status of the user 
      try {
        $user = User::find($userid);
        if($user->status)
         $user->update(['status'=> 0]);
         else
         $user->update(['status'=> 1]);
      } catch (\Throwable $th) {
       dd($th);
      }
   }
   public function  destroy($userid){ // destroy the user 

   try {
        User::destroy($userid);
   }
   catch (\Throwable $th) {
       dd($th);
   }
  }
}

Vue 模板

userslist.vue

<!-- resources/js/Pages/userlist.vue -->
<template>
   <div class="table-responsive">
        <table class="table">
              <thead>
                  <tr>
                      <th>SI.NO</th>
                      <th>Name</th>
                      <th>Email</th>
                      <th>Action</th>
                  </tr>
              </thead>
              <tbody>
                  <tr v-for="user, index in users" :key="user.id">
                      <td>{{ index + 1 }}</td>
                      <td>{{ user.name }}</td>
                      <td>{{ user.email }}</td>
                      <td>
                          <div class="form-check form-switch">
                              <input class="form-check-input" type="checkbox" :checked="user.status"
                                  @change="toggleStatus(user.id)" />
                          </div>

                      </td>
                      <td>
                          <button class="btn btn-danger" @click="deleteuser(user.id)">Delete</button>
                      </td>
                  </tr>
              </tbody>
          </table>
      </div>
</template>

脚本

Composition API vue 3 (提供/注入)

//resources/js/Pages/userlist.vue
import { onMounted, ref, getCurrentInstance,inject } from 'vue'
const controller=inject('controller') // inject the controller from the app
const controllerPath = "UserController"
        /*
         If The  UserController is inside the  admin folder,
         then the required Controller Path is admin/userController
         */
const users = ref([])
function toggleStatus(id) {
    controller(controllerPath, 'status', {
        userid: id,
    }).then(() => {
        alert('status changed');
    })
}
onMounted(() => {
    getUsers()
})
function deleteuser(id) {
    controller(controllerPath, 'destroy', {
        userid: id,
    }).then(() => {
        alert('User Deleted Successfully')
        getUsers();
    })
}
function getUsers() {
    controller(controllerPath, 'users')
        .then(response => {
            users.value = response.data.users
        })
}

Option API (全局属性)

//resources/js/Pages/userlist.vue
export default {
    data() {
        return {
            users: [],
            controllerPath: "UserController", 
            /*
            If The  UserController is inside the admin folder,
            then the required Controller Path is admin/userController
            */
        }
    },
    methods: {
        getUsers() {
            this.controller(this.controllerPath, 'users')
                .then(response => {
                    this.users = response.data.users
                })
        },
        deleteuser(id) {
            this.controller(this.controllerPath, 'destroy', {
                userid: id,     // passing userid as a params to the usercontroller destroy method
            }).then(() => {
                alert('User Deleted Successfully')
                this.getUsers();
            })
        },
        toggleStatus(id) {
            this.controller(this.controllerPath, 'status', {
                userid: id,  // passing userid as a params to the usercontroller status method
            }).then(() => {
                alert('status changed');
            })
        }
    },
    mounted() {
        this.getUsers()
    }
    }

供应商文件

vuecontroller.php 文件

namespace Yudhees\LaravelVueController;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Response;
class vuecontroller {
   public function __invoke(Request $request){
       $request->validate([
           'controller'=>'required',
           'function'=>'required',
       ]);
       $function=$request->function;
       $controller =  App::make("App\Http\Controllers\\{$request->controller}");
       if (!method_exists($controller, $function)) {
           return Response::json(['error' => 'Function does not exist'], 404);
       }
       $params=$request->params;
        return call_user_func_array([$controller, $function], $params);
   }
}

许可

laravel-vue-controller 是在 MIT 许可下发布的开源软件。有关更多信息,请参阅 LICENSE