精华内容
下载资源
问答
  • laravel 使用vue 介绍 ( Introduction ) Welcome back again Scotch.io readers, in today’s lesson we will be building a Guestbook that looks exactly like this: 再次欢迎Scotch.io读者,在今天的课程中,...

    laravel 使用vue

    介绍 ( Introduction )

    Welcome back again Scotch.io readers, in today’s lesson we will be building a Guestbook that looks exactly like this:

    再次欢迎Scotch.io读者,在今天的课程中,我们将构建一个如下所示的留言簿:

    GuestBook Preview

    It looks cool, doesn’t it?

    看起来很酷,不是吗?

    You will not only build the Guestbook but you will learn few things about both Laravel and Vue.js:

    您不仅将构建Guestbook,而且还将了解有关Laravel和Vue.js的一些知识:

    • New Laravel 5.5 Model Factory structure.

      Laravel 5.5模型工厂的新结构。
    • Testing API Endpoints with Postman and exporting them to be used by your teammates.

      使用Postman测试API端点并将其导出以供队友使用。
    • New Laravel 5.5 presets.

      新的Laravel 5.5预设
    • New Laravel 5.5 Transformers.

      新的Laravel 5.5变形金刚。
    • Creating and working with Vue.js components.

      创建和使用Vue.js组件。
    • Making Ajax calls with Laravel and Axios.

      使用Laravel和Axios进行Ajax调用。

    安装Laravel ( Installing Laravel )

    Installing Laravel is as simple as running a command in your terminal, cd into your www and execute:

    安装Laravel非常简单,只需在终端中运行命令,将CD插入www并执行:

    composer create-project --prefer-dist laravel/laravel guestbook

    After that, you will need to create a configuration file and point your domain name to the public folder ( for me it is gonna be http://guestbook.dev ) and make sure the storage and the bootstrap/cache directories are writable by your web server or Laravel will not run.

    之后,您将需要创建一个配置文件,并将您的域名指向公用文件夹(对我来说,它将是http://guestbook.dev ),并确保您的存储bootstrap / cache目录是可写的Web服务器或Laravel将无法运行。

    Note: Usually downloading Laravel via composer will set the application key for you, but if for whatever reason it didn’t work for you and you are getting either “No application encryption key has been specified.” or “The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.” running this command will fixed it for you:

    注意:通常通过composer下载Laravel会为您设置应用程序密钥,但是如果由于某种原因它对您不起作用,您将得到“未指定应用程序加密密钥”的信息。 或“唯一支持的密码是具有正确密钥长度的AES-128-CBC和AES-256-CBC。” 运行此命令将为您修复该问题:

    php artisan key:generate

    If you have done everything correctly then by browsing to http://guestbook.dev should see this exact same page:

    如果您已正确完成所有操作,则通过浏览至http://guestbook.dev,应会看到此页面完全相同:

    数据库配置 ( Database Configuration )

    Laravel’s database configurations are stored inside the environment variables file, to set your database information copy the content of .env.example to a .env file:

    Laravel的数据库配置存储在环境变量文件中,以设置数据库信息,将.env.example的内容复制到.env文件中:

    cp .env.example .env

    This is the part we are interested in:

    这是我们感兴趣的部分:

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=homestead
    DB_USERNAME=homestead
    DB_PASSWORD=secret

    For me, I will be using SQLite, that means I’ll set the DB_CONNECTION to sqlite and remove the rest of the configs.

    对我来说,我将使用SQLite ,这意味着我将把DB_CONNECTION设置为sqlite并删除其余的配置。

    if you removed DB_DATABASE config key, Laravel will assume you are working with database located in database/database.sqlite. Make sure you create that by running:

    如果删除了DB_DATABASE配置键,Laravel将假定您正在使用位于database / database.sqlite中的数据库。 确保通过运行以下命令进行创建:

    touch database/database.sqlite

    模型与迁移 ( Models and Migrations )

    For the Guestbook we will only need one model and migration, Let’s name it Signature.

    对于Guestbook,我们只需要一个模型和迁移,我们将其命名为Signature

    To create both these files we can run:

    要创建这两个文件,我们可以运行:

    php artisan make:model Signature -m

    When passing the -m flag to the php artisan make:model command a migration will be generated for you. This little trick will save you a lot of time and keystrokes.

    当将-m标志传递给php artisan make:model命令时,将为您生成一个迁移。 这个小技巧将为您节省很多时间和按键。

    Here is what our migration will look like:

    这是我们的迁移结果:

    class CreateSignaturesTable extends Migration
    {
        /**
         **_ Run the migrations.
         _**
         **_ @return void
         _**/
        public function up()
        {
            Schema::create('signatures', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->string('email');
                $table->text('body');
                $table->timestamp('flagged_at')->nullable();
                $table->timestamps();
            });
        }
    
        /**
         _ Reverse the migrations.
         _
         _ @return void
         _/
        public function down()
        {
            Schema::dropIfExists('signatures');
        }
    }

    The column names are self explanatory but if you are confused about what flagged_at does, it’s basically a timestamp column that will hold the date and time for when the signature got flagged/reported and it can be null for when the post hasn’t been flagged, pretty much the same way created_at, updated_at and deleted_at works.

    列名是不言自明的,但是如果您对flagged_at的操作感到困惑,那么它基本上是一个时间戳列,它将保存标记/报告签名的日期和时间,对于未标记该帖子的日期和时间可以为null ,几乎与created_atupdated_atDeleted_at的工作方式相同。

    Update your migration file, hit save and run the migration command:

    更新您的迁移文件,点击保存并运行迁移命令:

    php artisan migrate

    Last thing on this chapter is adding our columns to the fillable array on the model itself to allow for mass-assignment.

    本章的最后一件事是将我们的列添加到模型本身的可填充数组中,以允许进行质量分配。

    /_*
    _ Field to be mass-assigned.
    _
    _ @var array
    */
    protected $fillable = ['name', 'email', 'body', 'flagged_at'];

    If you don’t know what that means or what does it do, here’s a good explanation from the docs:

    如果您不知道这意味着什么或做什么,那么这是文档中的一个很好的解释:

    A mass-assignment vulnerability occurs when a user passes an unexpected HTTP parameter through a request, and that parameter changes a column in your database you did not expect. For example, a malicious user might send an is_admin parameter through an HTTP request, which is then passed into your model's create method, allowing the user to escalate themselves to an administrator.

    当用户通过请求传递意外的HTTP参数,并且该参数更改了数据库中您没有期望的列时,就会发生批量分配漏洞。 例如,恶意用户可能通过HTTP请求发送is_admin参数,然后将其传递到模型的create方法中,从而允许用户将自己升级为管理员。

    模型工厂 ( Model Factories )

    Next step would be generating dummy data to work with and we will be using Laravel Model Factories for that, Luckily for us Laravel 5.5 comes with a much cleaner way of storing these factories by putting each factory on its own file and giving us the ability to generate them using the command line.

    下一步将生成要使用的伪数据,为此,我们将使用Laravel模型工厂 。幸运的是,Laravel 5.5通过将每个工厂放在自己的文件中并使我们能够使用命令行生成它们。

    So let’s go ahead and run:

    因此,让我们继续运行:

    php artisan make:factory SignatureFactory

    And use Faker to get fake data that matches our table structure:

    并使用Faker获取与我们的表结构匹配的伪造数据:

    $factory->define(App\Signature::class, function (Faker $faker) {
        return [
            'name' => $faker->name,
            'email' => $faker->safeEmail,
            'body' => $faker->sentence
        ];
    });

    Our Signature model factory is ready, it’s time to generate some dummy data.

    我们的签名模型工厂已经准备就绪,是时候生成一些虚拟数据了。

    In your command line run: php artisan tinker Then:

    在命令行中运行: php artisan tinker然后:

    factory(App\Signature::class, 100)->create();

    You can create as many records as you want by replacing 100 with a number of your choice.

    您可以根据需要选择任意数量的100来创建任意数量的记录。

    路线和控制器 ( Routes and Controllers )

    定义路线 (Defining Our Routes)

    We can define these three routes by registering a new resource and excluding the ones we won’t be using:

    我们可以通过注册一个新资源并排除我们将不使用的资源来定义这三个路由:

    • GET: api/signatures this endpoint is responsible for fetching all signatures.

      GET: api / signatures此终结点负责获取所有签名。

    • GET: api/signature/:id this endpoint is responsible for fetching a single signature by its ID.

      GET: api / signature /:id此端点负责通过其ID提取单个签名。

    • POST: api/signatures this is the endpoint we will be hitting to save a new signature.

      POST: api / signatures这是我们将要保存新签名的端点。

    routes/api.php:

    路线/api.php:

    Route::resource('signatures', 'Api\SignatureController')
        ->only(['index', 'store', 'show']);
    • PUT: api/:id/report this endpoint is the one we will use to report a signature.

      PUT: api /:id / report此端点是我们将用来报告签名的端点。

    routes/api.php

    路线/api.php

    Route::put('signatures/{signature}/report', 'Api\ReportSignature@update');

    创建控制器 (Creating The Controllers)

    As you can already see in the routes definition section, the controllers we will need are SignatureController and ReportSignature.

    如您在路由定义部分中已经看到的那样,我们将需要的控制器是SignatureControllerReportSignature

    • Generating and writing SignatureController

      生成和编写SignatureController
    php artisan make:controller Api/SignatureController

    And this is what it will contain:

    这将包含以下内容:

    <?php
    
    namespace App\Http\Controllers\Api;
    
    use App\Signature;
    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use App\Http\Resources\SignatureResource;
    
    class SignatureController extends Controller
    {
        /**
         **_ Return a paginated list of signatures.
         _**
         **_ @return SignatureResource
         _**/
        public function index()
        {
            $signatures = Signature::latest()
                ->ignoreFlagged()
                ->paginate(20);
    
            return SignatureResource::collection($signatures);
        }
    
        /**
         _ Fetch and return the signature.
         _
         _ @param Signature $signature
         _ @return SignatureResource
         _/
        public function show(Signature $signature)
        {
            return new SignatureResource($signature);
        }
    
        /**
         _ Validate and save a new signature to the database.
         _
         _ @param Request $request
         _ @return SignatureResource
         _/
        public function store(Request $request)
        {
            $signature = $this->validate($request, [
                'name' => 'required|min:3|max:50',
                'email' => 'required|email',
                'body' => 'required|min:3'
            ]);
    
            $signature = Signature::create($signature);
    
            return new SignatureResource($signature);
        }
    }

    As you can see in our index method, we are using a scope with the name of ignoreFlagged to only return the signatures that hasn’t been flagged. You can define it by adding these lines to your Signature Model:

    如您在索引方法中所看到的,我们正在使用名称为ignoreFlagged的作用域仅返回未标记的签名。 您可以通过将以下行添加到签名模型来定义它:

    /_*
     _ Ignore flagged signatures.
     _
     _ @param $query
     _ @return mixed
     _/
    public function scopeIgnoreFlagged($query)
    {
        return $query->where('flagged_at', null);
    }
    • Generating and writing ReportSignature

      生成并编写ReportSignature
    php artisan make:controller Api/ReportSignature

    And this is what it will contain:

    这将包含以下内容:

    <?php
    
    namespace App\Http\Controllers\Api;
    
    use App\Signature;
    use App\Http\Controllers\Controller;
    
    class ReportSignature extends Controller
    {
        /_*
         _ Flag the given signature.
         _
         _ @param Signature $signature
         _ @return Signature
         _/
        public function update(Signature $signature)
        {
            $signature->flag();
    
            return $signature;
        }
    }

    When we retrieve the signature using Laravel Model Binding feature we call a flag method on it which simply sets the flagged_at column value to the current datetime, same way Laravel Soft Delete works. You can add this functionality by defining this method in your Signature Model:

    当我们使用Laravel模型绑定功能检索签名时,我们在其上调用一个flag方法,该方法只是将flagged_at列值设置为当前日期时间,与Laravel Soft Delete的工作方式相同。 您可以通过在签名模型中定义以下方法来添加此功能:

    /_*
     _ Flag the given signature.
     _
     _ @return bool
     */
    public function flag()
    {
        return $this->update(['flagged_at' => \Carbon\Carbon::now()]);
    }

    创建变形金刚 ( Creating Transformers )

    Laravel 5.5 ships with a really cool feature, if you are familiar with creating APIs then you clearly know that you always need to transform your data and not actually exposing your database table structure to your clients because if you’ll break anything that is relying on your API if you changed your table structure and for security purposes too. Nothing good comes from exposing your database structure.

    Laravel 5.5附带了一个非常酷的功能,如果您熟悉创建API的话,那么您清楚地知道,您始终需要转换数据,而实际上并不需要向客户公开数据库表结构,因为如果您破坏了所有依赖的内容您的API(如果您更改了表结构以及出于安全目的)。 公开数据库结构无济于事。

    In our case we will only need a Signature transformer, to create it we can run this command:

    在我们的例子中,我们只需要一个签名转换器,就可以运行以下命令来创建它:

    php artisan make:resource SignatureResource

    And this will be its content:

    这将是其内容:

    <?php
    
    namespace App\Http\Resources;
    
    use Illuminate\Http\Resources\Json\Resource;
    
    class SignatureResource extends Resource
    {
        /_*
         _ Transform the resource into an array.
         _
         _ @param  \Illuminate\Http\Request
         _ @return array
         _/
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'name' => $this->name,
                'avatar' => $this->avatar,
                'body' => $this->body,
                'date' => $this->created_at->diffForHumans()
            ];
        }
    }

    Because we are calling an avatar property we don’t have, we need to write an accessor for it. Having this in our Signature Model is also perfect because we don’t want to expose our guests email addresses.

    因为我们正在调用一个没有的头像属性,所以我们需要为其编写一个访问器。 在我们的“ 签名模型”中使用它也很完美,因为我们不想公开来宾的电子邮件地址。

    /_*
     _ Get the user Gravatar by their email address.
     _
     _ @return string  */
    public function getAvatarAttribute()
    {
        return sprintf('https://www.gravatar.com/avatar/%s?s=100', md5($this->email));
    }

    用邮递员测试端点 ( Testing Endpoints With Postman )

    After creating our endpoints, controllers and transformers, it’s time to test it! Let’s make sure everything is working as we’d expect. You might be asking me “But, Rachid? Why are we using Postman? We can simply use our browser for this?” And yes! I agree with you; we can use our browser to test this API, but if you are not actually writing your tests ( which you should do BTW! ) then I recommend you to test it with Postman because at least you can save those tests and run them again instead of opening the browser every time you make a change.

    创建了端点,控制器和变压器之后,就该进行测试了! 让我们确保一切正常。 您可能会问我“但是,拉希德? 我们为什么要使用邮递员? 我们可以简单地使用我们的浏览器吗?” 是的! 我同意你的看法; 我们可以使用我们的浏览器来测试该API,但是如果您实际上并未编写测试(您应该这样做BTW!),那么我建议您使用Postman对其进行测试,因为至少您可以保存这些测试并再次运行它们,而不是每次进行更改时都打开浏览器。

    To install Postman, browse to their website Postman | Supercharge your API workflow and pick the one that will work for you based on your OS.

    要安装邮递员,请浏览其网站 增强您的API工作流程,并根据您的操作系统选择适合您的工作流程

    I created a collection named Scotch Guestbook and put all my tests in it, you can do the same by clicking the New button and selecting the Collection option

    我创建了一个名为Scotch Guestbook的集合,并将所有测试放入其中,您可以通过单击“ 新建”按钮并选择“ 集合”选项来执行相同的操作

    Give it a name, a description and hit Create:

    给它起一个名字,一个描述,然后点击Create

    After creating your test, click Save and give it a name, a description, select a collection and hit Save:

    创建测试后,点击保存,并为其命名,描述,选择一个集合并点击保存

    测试我们的API端点 (Testing Our API Endpoints)

    • List of all signatures:

      所有签名列表:

    • Finding a signature by its ID:

      通过其ID查找签名:

    • Creating a new signature:

      创建一个新的签名:

    • Reporting a signature:

      报告签名:

    I will include this collection with the project code source in GitHub.

    我将把这个集合与GitHub中的项目代码源一起包括在内。

    前端设置 ( The Frontend Setup )

    By now, we are pretty much done with backend, the only remaining thing is to link our back with the frontend.

    到现在为止,我们已经完成了后端的工作,剩下的唯一事情就是将我们的后端与前端连接起来。

    主页设置 (Homepage Setup)

    GET: / This is our GuestBook entry point, it is responsible for rendering the home page.

    GET: /这是我们的GuestBook入口点,它负责呈现主页。

    routes/web.php:

    路线/web.php:

    Route::get('/', 'SignaturesController@index')->name('home');

    Then we create our controller by running:

    然后,我们通过运行以下内容创建控制器:

    php artisan make:controller SignaturesController

    And this will be its content:

    这将是其内容:

    <?php
    
    namespace App\Http\Controllers;
    
    class SignaturesController extends Controller
    {
        /_*
         _ Display the GuestBook homepage.
         _
         _ @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
         */
        public function index()
        {
            return view('signatures.index');
        }
    }

    After that, we need to create our signatures.index view. Inside /resources/views/ create a master.blade.php file which will hold the website layout and allow for the other pages to extend it:

    之后,我们需要创建我们的signatures.index视图。 在/ resources / views /内创建一个master.blade.php文件,该文件将保存网站布局并允许其他页面扩展它:

    <!doctype html>
    <html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Scotch.io GuestBook</title>
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <link href="{{ mix('css/app.css') }}" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div id="app">
            <nav class="navbar navbar-findcond">
                <div class="container">
                    <div class="navbar-header">
                        <a class="navbar-brand" href="{{ route('home') }}">GuestBook</a>
                    </div>
                    <div class="collapse navbar-collapse" id="navbar">
                        <ul class="nav navbar-nav navbar-right">
                            <li class="active">
                                <a href="{{ route('sign') }}">Sign the GuestBook</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            @yield('content')
        </div>
        <script src="{{ mix('js/app.js') }}"></script>
    </body>
    </html>

    Then, we create a new view inside a signatures folder with the name of index.blade.php

    然后,我们在签名文件夹内创建一个新索引 ,名称为index.blade.php。

    @extends('master')
    
    @section('content')<div class="container">
            <div class="row">
                <div class="col-md-12">
                    <signatures></signatures>
                </div>
            </div>
        </div>
    @endsection

    签名创建页面设置 (Signature Creation Page Setup)

    • GET: /sign This page is responsible for displaying the form for creating a new signature.

      GET: / sign此页面负责显示用于创建新签名的表单。
    Route::get('sign', 'SignaturesController@create')->name('sign');

    We have already created that controller, so let’s add this method to it:

    我们已经创建了该控制器,因此让我们向其添加此方法:

    /_*
     _ Display the GuestBook form page.
     _
     _ @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        return view('signatures.sign');
    }

    And the view will be named sign.blade.php and located at resources/views/signatures/

    该视图将被命名为sign.blade.php ,位于资源/视图/签名/

    @extends('master')
    
    @section('content')<div class="container">
            <div class="row">
                <div class="col-md-12">
                    <signature-form></signature-form>
                </div>
            </div>
        </div>
    @endsection

    使用Laravel预设 ( Working With Laravel Presets )

    Before 5.5, Laravel has shipped with Bootstrap and Vue.js scaffolding, but not everyone wants to use either of those technologies, so with Laravel 5.5 you can now replace those with the ones you like simply by running this to switch to React

    在5.5之前的版本中,Laravel附带了Bootstrap和Vue.js脚手架,但是并不是每个人都想使用其中任何一种技术,因此,通过Laravel 5.5,您现在可以简单地通过运行此程序以切换到React来用您喜欢的技术替换它们。

    php artisan preset react

    Or this if you are only interested in Bootstrap but not in any of those JS Frameworks:

    如果您仅对Bootstrap感兴趣,而对那些JS框架都不感兴趣,则可以这样做:

    php artisan preset bootstrap

    Or you can run this if you don’t want any scaffolding to be generated out of the box by Laravel:

    或者,如果您不希望Laravel开箱即用地生成任何脚手架,则可以运行此命令:

    php artisan preset none

    In our case, we will keep Vue.js and Bootstrap preset, so go ahead and run to install our JavaScript dependencies:

    在我们的例子中,我们将保留Vue.js和Bootstrap的预设,因此继续安装我们JavaScript依赖项:

    npm install

    Open /resources/assets//sass/app.scss and add this styling I already created for our project

    打开/resources/assets//sass/app.scss并添加我已经为我们的项目创建的样式

    $color_1: #f14444;
    $color_2: #444;
    $color_3: #fff;
    $border_color_1: #ccc;
    $border_color_2: #fff;
    $border_color_3: #f14444;
    
    nav.navbar-findcond {
      background: #fff;
      border-color: $border_color_1;
      box-shadow: 0 0 2px 0 #ccc;
      a {
        color: $color_1;
      }
      ul.navbar-nav {
        a {
          color: $color_1;
          border-style: solid;
          border-width: 0 0 2px 0;
          border-color: $border_color_2;
          &:hover {
            background: #fff;
            border-color: $border_color_3;
          }
          &:visited {
            background: #fff;
          }
          &:focus {
            background: #fff;
          }
          &:active {
            background: #fff;
          }
        }
      }
      ul.dropdown-menu {
        >li {
          >a {
            color: $color_2;
            &:hover {
              background: #f14444;
              color: $color_3;
            }
          }
        }
      }
    }
    button[type="submit"] {
      border-radius: 2px;
      color: $color_3;
      background: #e74c3c;
      padding: 10px;
      font-size: 13px;
      text-transform: uppercase;
      margin: 0;
      font-weight: 400;
      text-align: center;
      border: none;
      cursor: pointer;
      width: 10%;
      transition: background .5s;
      &:hover {
        background: #2f3c4e;
      }
    }

    Then run this command to compile it:

    然后运行以下命令进行编译:

    npm run dev

    Vue.js组件 ( Vue.js Components )

    At this point, the only thing remaining before we launch our amazing app is to create the two components we referenced:

    在这一点上,我们启动惊人的应用程序之前剩下的唯一事情就是创建我们引用的两个组件:

    <signatures></signatures> <!-- In index.blade.php -->
    <signature-form></signature-form> <!-- In sign.blade.php -->

    Go ahead and create those two files in /resources/assets/components/js/

    继续在/ resources / assets / components / js /中创建这两个文件

    • Signatures.vue

      签名
    <template>
        <div>
            // Our HTML template
        </div>
    </template>
    
    <script>
        export default {
            // Our Javascript logic
        }
    </script>
    • SignatureForm.vue

      SignatureForm.vue
    <template>
        <div>
            // Our HTML template
        </div>
    </template>
    
    <script>
        export default {
            // Our Javascript logic
        }
    </script>

    And register them ( right before we create the new Vue instance ) so that our app can know about them. Open /resources/assets/app.js

    并注册它们(在创建新的Vue实例之前),以便我们的应用程序可以了解它们。 打开/resources/assets/app.js

    Vue.component('signatures', require('./components/Signatures.vue'));
    Vue.component('signature-form', require('./components/SignatureForm.vue'));
    
    const app = new Vue({
        el: '#app'
    });

    显示所有签名 ( Displaying All Signatures )

    To display a paginated list of signatures, I will be using this package you can install it by running this command:

    要显示签名的分页列表,我将使用此软件包,您可以通过运行以下命令来安装它:

    npm install vuejs-paginate --save

    Register it in our /resources/assets/app.js file

    在我们的/resources/assets/app.js文件中注册

    Vue.component('paginate', require('vuejs-paginate'));

    And this will be content of our Signatures component:

    这将是我们签名组件的内容:

    <template>
        <div>
            <div class="panel panel-default" v-for="signature in signatures">
                <div class="panel-heading">
                    <span class="glyphicon glyphicon-user" id="start"></span>
                    <label id="started">By</label> {{ signature.name }}
                </div>
                <div class="panel-body">
                    <div class="col-md-2">
                        <div class="thumbnail">
                            <img :src="signature.avatar" :alt="signature.name">
                        </div>
                    </div>
                    <p>{{ signature.body }}</p>
                </div>
                <div class="panel-footer">
                    <span class="glyphicon glyphicon-calendar" id="visit"></span> {{ signature.date }} |
                    <span class="glyphicon glyphicon-flag" id="comment"></span>
                    <a href="#" id="comments" @click="report(signature.id)">Report</a>
                </div>
            </div>
            <paginate
                    :page-count="pageCount"
                    :click-handler="fetch"
                    :prev-text="'Prev'"
                    :next-text="'Next'"
                    :container-class="'pagination'">
            </paginate>
        </div>
    </template>
    
    <script>
        export default {
    
            data() {
                return {
                    signatures: [],
                    pageCount: 1,
                    endpoint: 'api/signatures?page='
                };
            },
    
            created() {
                this.fetch();
            },
    
            methods: {
                fetch(page = 1) {
                    axios.get(this.endpoint + page)
                        .then(({data}) => {
                            this.signatures = data.data;
                            this.pageCount = data.meta.last_page;
                        });
                },
    
                report(id) {
                    if(confirm('Are you sure you want to report this signature?')) {
                        axios.put('api/signatures/'+id+'/report')
                        .then(response => this.removeSignature(id));
                    }
                },
    
                removeSignature(id) {
                    this.signatures = _.remove(this.signatures, function (signature) {
                        return signature.id !== id;
                    });
                }
            }
        }
    </script>

    As you can see above, when the component gets created we call the fetch method which is making a GET request to the endpoint we defined in the data object, then we set our signatures array to the value returned from our API.

    正如您在上面看到的那样,当创建组件时,我们调用fetch方法,该方法向在数据对象中定义的端点发出GET请求,然后将签名数组设置为从API返回的值。

    In our HTML, we iterate through the signatures and display them. When a user clicks on the report link we fire the report method which takes the ID of the signature as a param and makes a PUT request to hide the reported signature and calls the removeSignature which is responsible of removing it from the array.

    在我们HTML中,我们遍历签名并显示它们。 当用户单击报告链接时,我们将启动报告方法,该方法将签名的ID作为参数,并发出PUT请求以隐藏报告的签名,并调用removeSignature ,该签名负责将其从数组中删除。

    签署访客留言簿 ( Sign the GuestBook )

    For the SignatureForm component, we created the form, bound our inputs to our data object. When the guest fills in the form and clicks the submit button we fire a POST request to save the new signature, if everything goes well we change our saved property to true and reset the form, if not we assign our errors property to whatever Laravel Validation returns and display them.

    对于SignatureForm组件,我们创建了表单,将输入绑定到数据对象 。 当访客填写表单并单击提交按钮时,我们会发出POST请求以保存新签名,如果一切顺利,我们将保存的属性更改为true并重置表单,否则,我们将errors属性分配给任何Laravel验证返回并显示它们。

    <template>
        <div>
            <div class="alert alert-success" v-if="saved">
                <strong>Success!</strong> Your signature has been saved successfully.
            </div>
    
            <div class="well well-sm" id="signature-form">
                <form class="form-horizontal" method="post" @submit.prevent="onSubmit">
                    <fieldset>
                        <legend class="text-center">Sign the GuestBook</legend>
    
                        <div class="form-group">
                            <label class="col-md-3 control-label" for="name">Name</label>
                            <div class="col-md-9" :class="{'has-error': errors.name}">
                                <input id="name"
                                       v-model="signature.name"
                                       type="text"
                                       placeholder="Your name"
                                       class="form-control">
                                <span v-if="errors.name" class="help-block text-danger">{{ errors.name[0] }}</span>
                            </div>
                        </div>
    
                        <div class="form-group">
                            <label class="col-md-3 control-label" for="email">Your E-mail</label>
                            <div class="col-md-9" :class="{'has-error': errors.email}">
                                <input id="email"
                                       v-model="signature.email"
                                       type="text"
                                       placeholder="Your email"
                                       class="form-control">
                                <span v-if="errors.email" class="help-block text-danger">{{ errors.email[0] }}</span>
                            </div>
                        </div>
    
                        <div class="form-group">
                            <label class="col-md-3 control-label" for="body">Your message</label>
                            <div class="col-md-9" :class="{'has-error': errors.body}">
                                        <textarea class="form-control"
                                                  id="body"
                                                  v-model="signature.body"
                                                  placeholder="Please enter your message here..."
                                                  rows="5"></textarea>
                                <span v-if="errors.body" class="help-block text-danger">{{ errors.body[0] }}</span>
                            </div>
                        </div>
    
                        <div class="form-group">
                            <div class="col-md-12 text-right">
                                <button type="submit" class="btn btn-primary btn-lg">Submit</button>
                            </div>
                        </div>
                    </fieldset>
                </form>
            </div>
        </div>
    </template>
    
    <script>
        export default {
    
            data() {
                return {
                    errors: [],
                    saved: false,
                    signature: {
                        name: null,
                        email: null,
                        body: null,
                    }
                };
            },
    
            methods: {
                onSubmit() {
                    this.saved = false;
    
                    axios.post('api/signatures', this.signature)
                        .then(({data}) => this.setSuccessMessage())
                        .catch(({response}) => this.setErrors(response));
                },
    
                setErrors(response) {
                    this.errors = response.data.errors;
                },
    
                setSuccessMessage() {
                    this.reset();
                    this.saved = true;
                },
    
                reset() {
                    this.errors = [];
                    this.signature = {name: null, email: null, body: null};
                }
            }
        }
    </script>

    After creating these two components or making changes to them, don’t forget to run this command to compile them.

    创建这两个组件或对其进行更改后,请不要忘记运行此命令来对其进行编译。

    npm run dev

    最后的话 ( Final Word )

    I hope you learnt a thing or two from this post, if you are working along and faced an issue I can help with, please do comment below and let me know of it. If you want to have a chat, I am RashidLaasri on Twitter, come and say Hi!

    希望您能从这篇文章中学到一两件事,如果您正在努力解决遇到的问题,我可以为您提供帮助,请在下面进行评论,并让我知道。 如果您想聊天,我是Twitter上的RashidLaasri ,快来打个招呼!

    Stay tuned for more Vue.js tutorials and see you soon!

    请继续关注更多Vue.js教程,很快再见!

    翻译自: https://scotch.io/tutorials/build-a-guestbook-with-laravel-and-vuejs

    laravel 使用vue

    展开全文
  • laravel 使用 vue

    2020-04-07 20:14:30
    引入app.js app.css app.js require('./bootstrap'); window.Vue = require('vue'); Vue.component('example', require('./components/Example.vue')); const app = new Vue({ el: '#app' }); 使用cnpm run watch

    引入app.js app.css

    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <script src="{{asset('js/app.js')}}"></script>
    
    
    <div id="app">
        <example></example>
    
    </div>

    app.js

    
    require('./bootstrap');
    
    window.Vue = require('vue');
    
    
    
    Vue.component('example', require('./components/Example.vue'));
    
    const app = new Vue({
        el: '#app'
    });
    

    使用cnpm run watch

    展开全文
  • laravel 使用vueIt's been a while since I wrote about Laravel and thought I should do something fun with it. In this tutorial, I will show you how to build a web-based chat application using Laravel ...

    laravel 使用vue

    It's been a while since I wrote about Laravel and thought I should do something fun with it. In this tutorial, I will show you how to build a web-based chat application using Laravel and Vue.js quickly. With a simple step by step guide, you will be able to create a system that supports user authentication and authorization before participating in a chat session.

    自从我写了有关Laravel的文章以来,已经有一段时间了,我认为我应该对此做些有趣的事情。 在本教程中,我将向您展示如何使用Laravel和Vue.js快速构建基于Web的聊天应用程序。 借助简单的分步指南,您将能够创建一个支持用户身份验证和授权的系统,然后再参与聊天会话。

    Due to the fact that Laravel is shipped with Vue.js by default, It is very easy to build single-page applications, handle frontend logic by creating Vue components and use them like you would use a regular HTML tag inside the blade template of Laravel.

    由于默认情况下Laravel随Vue.js一起提供,因此很容易构建单页应用程序,通过创建Vue组件来处理前端逻辑并像使用Laravel刀片模板中的常规HTML标签一样使用它们。

    To make this chat application fully functional, you will leverage CometChat chat infrastructure to enhance the sharing of instant messages.

    为了使此聊天应用程序充分发挥功能,您将利用CometChat聊天基础结构来增强即时消息的共享。

    我们将建立什么 ( What we will build )

    At the end of this tutorial, you would have built a system that will allow users to send and receive messages in realtime, as shown below:

    在本教程的最后,您将构建一个系统,该系统将允许用户实时发送和接收消息,如下所示:

    To join a chat session, a user will have to provide a unique username and password as credentials during the registration process, afterward, such user will be created on CometChat as well. This means when registering a new user within your application, the details of such users will be saved in your local database first and then sent to the CometChat server using its REST API. Laravel will be used to build a backend API needed for these processes and make provisions of endpoints for Vue.js on the frontend.

    要加入聊天会话,用户将必须在注册过程中提供唯一的usernamepassword作为凭据,然后,还将在CometChat上创建该用户。 这意味着在应用程序中注册新用户时,这些用户的详细信息将首先保存在本地数据库中,然后使用其REST API发送到CometChat服务器。 Laravel将用于构建这些流程所需的后端API,并在前端为Vue.js设置端点。

    If you would love to try out the working demo for this tutorial, you can download the complete source code here on GitHub.

    如果您想尝试本教程的工作演示,可以在GitHub上下载完整的源代码。

    先决条件 ( Prerequisites )

    Before proceeding, this tutorial assumes you have:

    在继续之前,本教程假定您具有:

    • A PHP development environment setup.

      PHP开发环境设置。
    • Git installed on your computer. Follow this link to download Git if otherwise

      安装在计算机上的Git。 否则,请点击链接下载Git
    • A global installation of composer, which will be used to install all dependencies for the project.
      • Note: Homebrew users can install composer by running brew install composer##

      全局安装composer ,它将用于安装项目的所有依赖项。
      • 注意:自制软件用户可以通过运行brew install composer ##来安装composer。

    CometChat? ( CometChat? )

    CometChat is a developer platform that allows you to easily integrate chat features and building a realtime chat widget for a new or existing web and mobile application. It is a developer tool that makes implementing features such as;

    CometChat是一个开发人员平台,可让您轻松集成聊天功能并为新的或现有的Web和移动应用程序构建实时聊天小部件。 它是一个开发人员工具,可实现以下功能:

    • Group chat

      群聊
    • One on One chat

      一对一聊天
    • Typing indicators

      打字指标
    • Read and delivered indicators

      阅读和交付指标
    • and a whole lot more, easy to craft.

      还有很多,易于制作。

    You can read more about CometChat here on Comet’s official website.

    您可以在Comet的官方网站上了解有关CometChat的更多信息。

    CometChat的身份验证流程 ( CometChat’s authentication flow )

    It is compulsory that one must be authenticated as a user before you can make use of infrastructure made available by CometChat.

    必须强制经过身份验证的用户才能使用CometChat提供的基础结构。

    As proof of concept or to test a demo application, you can make use of the sample users that are being generated automatically for every new application created on CometChat. But for a production-ready application, it is advisable to take it a step further by making use of our REST API to programmatically create unique users, as you would see later in the tutorial.

    作为概念验证或测试演示应用程序,您可以利用为CometChat上创建的每个新应用程序自动生成的样本用户。 但是对于可用于生产环境的应用程序,建议您进一步使用REST API,以编程方式创建唯一用户,这将使您走得更远,就像您将在本教程的后面看到的那样。

    Once a user is in place, authenticating such a user to CometChat, is as simple as calling the CometChat.login() the method from the JavaScript SDK. Before this method can work properly, you can either use the user’s UID and the auth-only secret key as a parameter for the CometChat.login() , or you can generate a unique auth token on CometChat via its REST API and use the generated token as they require a parameter.

    一旦用户就位,对此类用户进行CometChat身份验证就像从JavaScript SDK调用CometChat.login()方法一样简单。 在此方法正常工作之前,您可以将用户的UID和仅身份验证密钥用作CometChat.login()的参数,也可以通过CometChat的REST API生成唯一的身份验证令牌,然后使用生成的令牌,因为它们需要参数。

    For the purpose of this tutorial, you will learn how to use the auth token for authenticating a user.

    就本教程而言,您将学习如何使用auth令牌来认证用户。

    使用Laravel创建身份验证服务器 ( Creating an authentication server using Laravel )

    While CometChat can handle the login process of users from your application, It is important to note that CometChat SDK can only maintain the session of the logged-in user within the SDK and will not be able to handle user authentication for your application. So here, you will build an authentication server using Laravel.

    尽管CometChat可以处理您应用程序中用户的登录过程,但需要注意的是CometChat SDK只能维护SDK中已登录用户的会话,而不能处理应用程序的用户身份验证。 因此,在这里,您将使用Laravel构建身份验证服务器。

    设置Laravel应用程序 ( Setting up the Laravel application )

    The get started easily, you are going to set up a group chat application on top of a Laravel 5.8 application on GitHub. This starter template already contains the required assets, stylesheet, and a couple of dependencies for the app.

    轻松入门,您将在GitHub上的Laravel 5.8应用程序之上设置一个群聊应用程序。 该入门模板已经包含所需的资产,样式表以及该应用程序的几个依赖项。

    You will be making use of Git to clone this repository and gradually add more code to make it fully functional.

    您将利用Git克隆此存储库,并逐步添加更多代码以使其完全起作用。

    To begin, from the terminal in your machine, navigate to your preferred project directory and run the following command to clone the starter template from GitHub:

    首先,从您机器上的终端,导航到您的首选项目目录,然后运行以下命令从GitHub克隆入门模板:

    // Clone repositorygit clone https://github.com/christiannwamba/lara-chat-app-starter.git

    Next, move into the newly created project:

    接下来,进入新创建的项目:

    cd lara-chat-app-starter

    and install all the dependencies for Laravel using composer by running the following command:

    并通过运行以下命令使用composer安装Laravel的所有依赖项:

    composerinstall

    Now, create a .env file and then copy the content of .env.example into it:

    现在,创建一个.env文件,然后将.env.example的内容复制到其中:

    // create a .envfile
    touch .env
    
    // update its content
    cp .env.example .env

    Generate a key for your project using the artisan command:

    使用artisan命令为您的项目生成密钥:

    php artisan key:generate

    Once you are done, the next step is to create a connection to your database. To achieve that, open the .env file and update the DB_DATABASE, DB_USERNAME and DB_PASSWORD values with the appropriate contents.

    完成后,下一步就是创建与数据库的连接。 为此,请打开.env文件,并使用适当的内容更新DB_DATABASEDB_USERNAMEDB_PASSWORD值。

    💡 To avoid running into any error, ensure that you have created a database before running the next command.

    💡为了避免遇到任何错误,请确保在运行下一个命令之前已创建数据库。

    After successfully completing this basic setup, you can now proceed to generate the database structure for your application using the following command:

    成功完成此基本设置之后,您现在可以使用以下命令继续为您的应用程序生成数据库结构:

    php artisan migrate

    The preceding command will run the migration file located in database/migrations/ with a file name that looks like this 2014_10_12_000000_create_users_table.php`` and create aUsers\ table with the appropriate fields.

    前面的命令将运行位于database/migrations/的迁移文件,其文件名如下所示: 2014_10_12_000000 _create_users_table.php``并使用适当的字段创建Users\表。

    创建路线 ( Creating routes )

    In chronological order, what you want to achieve with the backend of this application is to create endpoints with the purpose of handling three different functionalities:

    按照时间顺序,您希望使用此应用程序的后端实现的目的是创建端点,以处理三种不同的功能:

    • Registering a user

      注册用户
    • Logging in user into your application

      将用户登录到您的应用程序
    • Saving a unique auth token for each user.

      为每个用户保存一个唯一的身份验证令牌。

    Since the intention is to build the backend as an API that will be consumed by Vue.js (Frontend), it is absolutely fine to make use of the routes specifically created for that purpose by Laravel. First, open the routes/web.php file and ensure that the content in it is the same as what you have below. Otherwise, update its content with:

    由于目的是将后端构建为Vue.js(Frontend)将使用的API,因此绝对可以使用Laravel为此目的专门创建的路由。 首先,打开routes/web.php文件,并确保其中的内容与下面的内容相同。 否则,请使用以下命令更新其内容:

    // routes/web.php
    
    Route::get('/{any}', function () {
        return view('layouts.master');
    })->where('any','.*');

    The code snippet above was used to register a route that can respond to all HTTP verbs. This is ideal for this application as all the routing will be handled by Vue.js, and Laravel will only render a single master layout view named layouts.master. You will create this file in a bit. Next, in routes/api.php, add the following routes to the list:

    上面的代码段用于注册可以响应所有HTTP动词的路由。 这对于该应用程序是理想的,因为所有路由都将由Vue.js处理,并且Laravel将仅呈现一个名为layouts.master主布局视图。 您将稍后创建此文件。 接下来,在routes/api.php ,将以下路由添加到列表中:

    // routes/web.php
    Route::post('/register', 'UserController@register')->middleware('guest');
    Route::post('/login', 'UserController@login')->middleware('guest');
    Route::post('/update/token', 'UserController@updateToken');

    创建用户控制器 ( Create the User Controller )

    From your terminal, ensure that you are still within the root directory of the application and run the following command that will create a new UserController:

    在终端上,确保您仍在应用程序的根目录中,并运行以下命令将创建一个新的UserController

    php artisan make:controller UserController

    You will see the following output in the terminal:

    您将在终端中看到以下输出:

    Controller created successfully

    This will automatically generate a new file named UserController.php located in app/Http/UserController.php. Inside this controller class, you will add the following methods to match your project routes: register, login, updateToken.

    这将自动在app/Http/UserController.php生成一个名为UserController.php的新文件。 在此控制器类内,您将添加以下方法以匹配您的项目路线: registerloginupdateToken

    Register a user Here, you will implement the logic to register a user for your application. Open the newly created app/Http/Controllers/UserController.php and update its content with the following:

    注册用户在这里,您将实现为应用程序注册用户的逻辑。 打开新创建的app/Http/Controllers/UserController.php并使用以下内容更新其内容:

    // app/Http/Controllers/UserController.php<?php
    namespace App\Http\Controllers;
    
    use App\User;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Hash;
    
    class UserController extends Controller
    {
    
        public function register(Request $request) {
            $username = $request->get('username');
            $password = $request->get('password');
    
            if ($this->checkIfUserExist($username)) {
                return response()->json([
                    'message' => 'User already exist'
                ], 500);
            } else {
                $password = bcrypt($password);
                User::create([
                    'username' => $username,
                    'password' => $password
                ]);
                return response()->json(true);
            }
        }
    
        private function checkIfUserExist($username) {
            $user = User::where('username', $username)->first();
    
            if ($user) {
                return $user;
            } else {
                return false;
            }
        }
    }

    The method above uses Laravel’s Request method to obtain the username and password of a particular user. And then, there is a check carried out to note if such a user exists in the database by calling a private method checkIfUserExist(), which will either return the User object if it exist or false if otherwise.

    上面的方法使用Laravel的Request 方法来获取特定用户的用户usernamepassword 。 然后,通过调用私有方法checkIfUserExist()进行检查以记录该用户是否存在于数据库中,该方法将返回User对象(如果存在checkIfUserExist() ,否则返回false

    Authenticate the user within the application Now add the login() to handle the authentication of users within the application:

    在应用程序中对用户进行身份验证现在添加login()来处理应用程序中的用户身份验证:

    public function login(Request $request) {
        $username = $request->get('username');
        $password = $request->get('password');
    
        $user = $this->checkIfUserExist($username);
    
        if ($user) {
            $confirmPassword = Hash::check($password, $user->password);
            return response()->json([
                'status' => $confirmPassword,
                'token' => $user->authToken
            ]);
        } else {
            return response()->json([
                'message' => "Invalid credentials"
            ], 500);
        }
    }

    Here, after grabbing the username and password of a particular user, you checked if the user exists in your project’s database. If found, you will confirm to ensure that the password hash matches the one that was provided by the user and then returns the auth token that was generated for the user during the registration process.

    在这里,获取特定用户的usernamepassword后,您检查了该用户是否存在于项目的数据库中。 如果找到,您将确认以确保密码哈希与用户提供的密码哈希匹配,然后返回在注册过程中为用户生成的身份验证令牌。

    Save Users’ token in the database One of the approaches to authenticate users in CometChat is by calling the CometChat.login() and passing a generated token to it as an argument. CometChat already made a provision to generate that on the fly through the REST API without much hassle. You will do that once you start the implementation of the frontend logic. To save the generated token for each user, add the following method to the UserController:

    在数据库中保存用户的令牌在 CometChat中对用户进行身份验证的方法之一是调用CometChat.login()并将生成的token作为参数传递给它。 CometChat已经做好了通过REST API快速生成该请求的规定。 一旦开始前端逻辑的实现,就将执行此操作。 要保存为每个用户生成的令牌,请将以下方法添加到UserController

    public function updateToken(Request $request) {
        $username = $request->get('uid');
        $token = $request->get('token');
    
        User::where('username', $username)->update([
            'authToken' => $token
        ]);
    }

    This will receive the generated Auth token for the user by CometChat and use Laravel eloquent to update the Database with the value.

    这将接收CometChat为用户生成的Auth token ,并雄辩地使用Laravel用值更新数据库。

    创建主布局 ( Create the master layout )

    Ensure that the file located in resources/views/layouts/master.blade.php contains the following contents:

    确保位于resources/views/layouts/master.blade.php中的文件包含以下内容:

    <!-- resources/views/layouts/master.blade.php -->
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <link rel="stylesheet" href="{{ asset('css/style.css') }}">
        <title>Laravel Chat Application</title>
    </head>
    <body>
    <div id="app">
        <App />
    </div>
    
    <script src="{{ asset('js/app.js') }}"></script>
    </body>
    </html>

    This is a basic HTML template with a link to the stylesheet and JavaScript file for the application. Also, a custom HTML tag <App /> representing the markup to render the AppComponent in the resources/js/App.vue files. The AppComponent is the entry point of the Vue.js application. More about this later in the tutorial.

    这是一个基本HTML模板,带有指向应用程序的样式表和JavaScript文件的链接。 另外,一个自定义HTML标记<App />表示标记,用于在resources/js/App.vue文件中呈现resources/js/App.vueAppComponent是Vue.js应用程序的入口点。 本教程后面的内容将对此进行更多介绍。

    Now that you are done setting up the contents required for the Backend, you can now proceed to create the structure for the frontend of the application.

    既然您已经完成了设置后端所需的内容,那么现在可以继续为应用程序的前端创建结构了。

    前端入门 ( Getting started with the frontend )

    Earlier, you started this project by downloading a starter template from GitHub. As mentioned, it contains some dependencies that you need to install for this application before you can proceed. You have already installed the dependencies for the Backend and now open another terminal from your project’s directory and run the following command to install the dependencies for the frontend using NPM:

    之前,您是通过从GitHub下载入门模板来启动该项目的。 如前所述,它包含一些必须为此应用程序安装的依赖项,然后才能继续。 您已经安装了后端的依赖关系,现在从项目目录中打开另一个终端,然后运行以下命令以使用NPM安装前端的依赖关系:

    // install dependencies 
    npm install

    Here is a list of some of the dependencies that will be installed from your package.json file:

    这是将从package.json文件中安装的一些依赖项的列表:

    • vue: Vue.js for building a single page application.

      vue :用于构建单页应用程序的Vue.js。
    • axios: A promise-based HTTP client for the browser

      axios :浏览器的基于promise的HTTP客户端
    • @cometchat-pro/chat: This is the JavaScript SDK for CometChat

      @cometchat-pro/chat :这是CometChatJavaScript SDK
    • vue-router: This is the official router for Vue.js

      vue-router :这是Vue.js的官方路由器

    Create a CometChat account To be able to use and integrate CometChat into your application, you need to create an account. Head over to CometChat website and create a free CometChat Pro account. Once you fill all the required information, you will have a trial account set up for you immediately. Now, proceed to your CometChat dashboard, then add a new app by choosing the stable version of CometChat SDK (v2) and select your preferred region, as it will be used as it will be required when initializing CometChat within your project, I have selected Europe for this tutorial. Next, enter a name for your app, then click on the + sign and wait for a couple of seconds for your new app to be created.

    创建一个CometChat帐户为了能够使用CometChat并将其集成到您的应用程序中,您需要创建一个帐户。 前往CometChat网站创建一个免费的CometChat Pro帐户 。 填写所有必需的信息后,您将立即为您设置一个试用帐户。 现在,进入您的CometChat仪表板 ,然后通过选择稳定版本的CometChat SDK(v2)添加一个新应用并选择您的首选区域,因为在您的项目中初始化CometChat时将需要使用该区域,因此我选择了Europe本教程。 接下来,为您的应用输入名称,然后单击+号,并等待几秒钟以创建新应用。

    Once your application is successfully created, click on Explore to open it and then go to the API Keys tab, copy both your APP ID and API Key (with full access scope) and save it somewhere. Also, by default, CometChat will automatically create a group with a unique GUID for your app. Click on Groups tab to access it and copy it as well.

    成功创建应用程序后,单击“ 浏览”将其打开,然后转到“ API密钥”选项卡,同时复制您的APP IDAPI密钥 (具有完全访问权限)并将其保存在某个位置。 另外,默认情况下,CometChat会自动为您的应用创建一个具有唯一GUID的组。 单击“ 组”选项卡以访问它并复制它。

    Next, back in your Laravel application, open the .env file and locate these variables:

    接下来,返回您的Laravel应用程序,打开.env文件并找到以下变量:

    MIX_COMMETCHAT_API_KEY=YOUR_COMMETCHAT_API_KEY
    MIX_COMMETCHAT_APP_ID=YOUR_COMMETCHAT_APP_ID
    MIX_COMMETCHAT_GUID=YOUR_COMMETCHAT_GUID

    Replace the YOUR_COMMETCHAT_API_KEY, YOUR_COMMETCHAT_APP_ID, YOUR_COMMETCHAT_GUID placeholder with the appropriate credentials as obtained from your CometChat dashboard. With that out of the way, you can now start setting up the group chat.

    用从CometChat仪表板获得的适当凭据替换YOUR_COMMETCHAT_API_KEYYOUR_COMMETCHAT_APP_IDYOUR_COMMETCHAT_GUID占位符。 现在,您可以开始设置群聊了。

    初始化CometChat ( Initialize CometChat )

    It is recommended by CometChat that your application must call the init() method from the JavaScript SDK once your app starts. This will enable your app to communicate with the CometChat server easily. To achieve that, navigate to resources/js/App.vue file and update the script section with the following code:

    CometChat建议您的应用程序启动后,您的应用程序必须从JavaScript SDK调用init()方法。 这将使您的应用轻松与CometChat服务器通信。 为此,请导航到resources/js/App.vue文件,并使用以下代码更新脚本部分:

    // resources/js/App.vue
    
    <script>
        import { CometChat } from "@cometchat-pro/chat";
        export default {
            created() {
                this.initializeApp();
            },
    
            methods: {
                initializeApp() {
                    let appID = process.env.MIX_COMMETCHAT_APP_ID;
    
                    let cometChatSettings = new CometChat.AppSettingsBuilder()
                        .subscribePresenceForAllUsers()
                        .setRegion("eu")
                        .build();
    
                    CometChat.init(appID, cometChatSettings).then(
                        () => {
                            console.log("Initialization completed successfully");
                        },
                        error => {
                            console.log("Initialization failed with error:", error);
                        }
                    );
                }
            }
        };
    </script>

    Here, you initialise CometChat with your unique APP_ID and REGION.

    在这里,您使用唯一的APP_IDREGION初始化CometChat。

    💡 If you chose the US as your region, write setRegion(“us”) instead of setRegion(“eu”) as did above

    💡如果您选择美国作为您的区域,请像上面一样写setRegion(“ us”)而不是setRegion(“ eu”)

    注册并创建一个新用户 ( Register and create a new user )

    The approach for this application is to register a user into your application and immediately create the same user programmatically in CometChat. You will achieve all these by using the REST API provided by CometChat once the registration process is successful within your application.

    此应用程序的方法是将用户注册到您的应用程序中,并立即在CometChat中以编程方式创建该用户。 一旦在应用程序中成功完成注册过程,您将使用CometChat提供的REST API来实现所有这些目标。

    To begin, you will create a new folder named views within resources/js folder. And within the newly created folder, create a new file and call it Register.vue. Open it and update its <template></template> section with the following content:

    首先,您将在resources/js文件夹中创建一个名为views的新文件夹。 在新创建的文件夹中,创建一个新文件,并将其命名为Register.vue 。 打开它并使用以下内容更新其<template></template>部分:

    // resources/js/views/Register.vue
    <template>
        <div class="login-page">
            <div class="login">
                <div class="register-container auth-container">
                    <div class="register-image-column">
                        <div class="image-holder">
                            <img src="../../assets/login-illustration.svg" alt="">
                        </div>
                    </div>
    
                    <div class="register-form-column">
                        <form v-on:submit.prevent="registerAppUser">
                            <h3>Create an Account</h3>
                            <div class="form-wrapper">
                                <label for="username">Username</label>
                                <input type="text" name="username" id="username" v-model="username" placeholder="Enter your username" class="form-control" required>
                            </div>
    
                            <div class="form-wrapper">
                                <label for="password">Password</label>
                                <input type="password" name="password" id="password" v-model="password" placeholder="Enter your password" class="form-control" required>
                            </div>
    
                            <div class="form-wrapper">
                                <label for="password_confirmation">Confirm Password</label>
                                <input type="password" name="password_confirmation" id="password_confirmation" v-model="password_confirmation" placeholder="Re-enter password" class="form-control" required>
                            </div>
                            <button type="submit">SIGN UP &nbsp;&nbsp;<span v-if="showSpinner" class="fa fa-spin fa-spinner"></span> </button>
                        </form>
    
                        <div class="text-center m-t-50 link-reg">
                            <p v-on:click="redirectToLogin">Do you have an account?  <span>Log in</span></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>

    The code snippet above contains input fields that will be used to obtain the username, password, and password_confirmation of a user during the registration process. The HTML form will call a method named registerAppUser() once submitted.

    上面的代码段包含输入字段,这些字段将用于在注册过程中获取usernamepasswordpassword_confirmation 。 提交后,HTML表单将调用名为registerAppUser()的方法。

    Now, within the <script></script> section of the Register Component, paste the following code:

    现在,在“注册组件”的<script></script>部分中,粘贴以下代码:

    // resources/js/views/Register.vue
    
    <script>
        export default {
            data() {
                return {
                    username: "",
                    password: '',
                    password_confirmation: '',
                    showSpinner: false,
                };
            },
            methods: {
                registerAppUser() {
                    if (this.username && this.password && this.password_confirmation) {
                        if (this.password && this.password_confirmation) {
                            let userData = {
                                username: this.username,
                                password: this.password,
                                password_confirmation: this.password_confirmation
                            };
    
                            axios.post(`http://localhost:8000/api/register`, userData)
                                .then(response => {
                                    if (response.data) {
                                        this.createUserOnCometChat(this.username);
                                    }
                                }).catch(error => {
                                alert(error.response.data.message);
                            })
                        }
                    }
                },
                redirectToLogin() {
                    this.$router.push({name: 'login'})
                }
            }
        };
    </script>

    Above, you defined the properties and corresponding initial values within the data option and then created the registerAppUser() method. This method obtained the username and password of a user and used axios to send it to the backend (Laravel). Once the user’s details are saved successfully, the backend API will return a successful response.

    上面,您在data选项中定义了属性和相应的初始值,然后创建了registerAppUser()方法。 此方法获取usernamepassword ,并使用axios将其发送到后端(Laravel)。 成功保存用户的详细信息后,后端API将返回成功的响应。

    If the registration process was successful, a new method to programmatically create the user on CometChat would be called.

    如果注册过程成功,则将调用在CometChat上以编程方式创建用户的新方法。

    Create a user on CometChat

    在CometChat上创建一个用户

    Add the following method to create the user on CometChat:

    添加以下方法在CometChat上创建用户:

    // resources/js/views/Register.vue
    
    async createUserOnCometChat(username) {
        let url = `https://api-eu.cometchat.io/v2.0/users`;
        let data = {
            uid: username,
            name: `${username} sample`,
            avatar: 'https://data-eu.cometchat.io/assets/images/avatars/captainamerica.png',
        };
    
        try {
            const userResponse = await fetch(url, {
                method: 'POST',
                headers: new Headers({
                    appid: process.env.MIX_COMMETCHAT_APP_ID,
                    apikey: process.env.MIX_COMMETCHAT_API_KEY,
                    'Content-Type': 'application/json'
                }),
                body: JSON.stringify(data),
            });
            const userJson = await userResponse.json();
    
            console.log('New User', userJson);
            this.createAuthTokenAndSaveForUser(username);
            this.redirectToLogin();
        } catch (error) {
            console.log('Error', error);
        }
    }

    This method takes the username of the registered user after a successful sign-up process and passes it along with a custom name to CometChat Create User API. After the user has been created successfully, another method to create an auth via the CometChat API for the new user was also invoked.

    成功注册后,此方法将使用注册用户的用户名,并将其与自定义名称一起传递给CometChat Create User API 。 成功创建用户后,还调用了另一种通过CometChat API为新用户创建身份验证的方法。

    Creating a new CometChat auth token Add the method below to create an auth token for the user and the token in your database once the process is completed:

    创建新的CometChat身份验证令牌添加该方法以在完成该过程后为用户和数据库中的令牌创建身份验证令牌:

    // resources/js/views/Register.vue
    
    async createAuthTokenAndSaveForUser(uid) {
        let url = `https://api-eu.cometchat.io/v2.0/users/${uid}/auth_tokens`;
    
        try {
            const tokenResponse = await fetch(url, {
                method: 'POST',
                headers: new Headers({
                    appid: process.env.MIX_COMMETCHAT_APP_ID,
                    apikey: process.env.MIX_COMMETCHAT_API_KEY,
                    'Content-Type': 'application/json'
                }),
            });
            const tokenJSON = await tokenResponse.json();
            this.addUserToAGroup(uid);
            this.sendTokenToServer(tokenJSON.data.authToken, tokenJSON.data.uid);
        } catch (error) {
            console.log('Error Token', error);
        }
    
    }

    Add user to a group CometChat has already created members for the default group for your application automatically. So, before users that are created through your Laravel application can participate in a chat session, they need to be added as a member. Use the following method to add users of your application to a group:

    将用户添加到组 CometChat已经为您的应用程序的默认组自动创建了成员。 因此,在通过Laravel应用程序创建的用户可以参与聊天会话之前,需要将他们添加为成员。 使用以下方法将您的应用程序的用户添加到组中:

    // resources/js/views/Register.vue
    
    async addUserToAGroup(uid) {
        let url = `https://api-eu.cometchat.io/v2.0/groups/${process.env.MIX_COMMETCHAT_GUID}/members`;
        let data = {
            "participants":[uid]
        };
    
        try {
            const groupResponse = await fetch(url, {
                method: 'POST',
                headers: new Headers({
                    appid: process.env.MIX_COMMETCHAT_APP_ID,
                    apikey: process.env.MIX_COMMETCHAT_API_KEY,
                    'Content-Type': 'application/json'
                }),
                body: JSON.stringify(data),
            });
            const groupJson = await groupResponse.json();
    
            console.log('Added to group', groupJson);
        } catch (error) {
            console.log('Error', error);
        }
    },

    Save AuthToken in database Having generated an AuthToken for your app users on CometChat, you need to save the token in the database for that particular user. With this in place, the token can be retrieved as part of the user's details when authenticating the user within your application. Add the method below for that purpose:

    将AuthToken保存在数据库中AuthToken为您的应用程序用户生成了AuthToken之后,您需要将特定用户的令牌保存在数据库中。 有了这个,在应用程序内对用户进行身份验证时,可以将令牌作为用户详细信息的一部分进行检索。 为此添加以下方法:

    // resources/js/views/Register.vue
    
    sendTokenToServer(token, uid) {
        axios.post(`http://localhost:8000/api/update/token`, {token, uid})
            .then(response => {
                console.log("Token updated successfully", response);
            }).catch(error => {
            alert(error.response.data.message);
        })
    }

    验证用户 ( Authenticating users )

    Since you can now register users, create such users on CometChat and add them as a member of a particular group through your application, you will now proceed to authenticate users within your application and also on CometChat.

    由于您现在可以注册用户,在CometChat上创建此类用户并通过您的应用程序将其添加为特定组的成员,因此您现在将继续在应用程序以及CometChat上对用户进行身份验证。

    To begin, create a new file within resources/js/views folder and name it Login.vue. Open the newly created file and update the <template></template> section with the following code:

    首先,在resources/js/views文件夹中创建一个新文件,并将其命名为Login.vue 。 打开新创建的文件,并使用以下代码更新<template></template>部分:

    // resources/js/views/Login.vue
    
    <template>
        <div class="login-page">
            <div class="login">
                <div class="login-container auth-container">
                    <div class="login-form-column">
                        <form v-on:submit.prevent="authLoginAppUser">
                            <h3>Hello!</h3>
                            <div class="form-wrapper">
                                <label>Username</label>
                                <input type="text" name="username" id="username" v-model="username" placeholder="Enter your username" class="form-control" required>
                            </div>
    
                            <div class="form-wrapper">
                                <label for="password">Password</label>
                                <input type="password" name="password" id="password" v-model="password" placeholder="******" class="form-control" required>
                            </div>
                            <button type="submit">LOG IN &nbsp;&nbsp;<span v-if="showSpinner" class="fa fa-spin fa-spinner"></span> </button>
                        </form>
    
                        <div class="text-center m-t-50 link-reg">
                            <p v-on:click="redirectToRegister">Don't have an account? <span>Register</span></p>
                        </div>
                    </div>
    
                    <div class="login-image-column">
                        <div class="image-holder">
                            <img src="../../assets/login-illustration.svg" alt="">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>

    Here, the HTML form will receive the inputted value for the username and password of a user and send it to be processed by the authLoginAppUser() method once the form is submitted. Next, use the content below to update the <script></script> section of the Login component:

    在此,HTML表单将接收usernamepassword的输入值,并在表单提交后将其发送给authLoginAppUser()方法进行处理。 接下来,使用以下内容更新“登录”组件的<script></script>部分:

    // resources/js/views/Login.vue
    <script>
        import { CometChat } from "@cometchat-pro/chat";
        export default {
            data() {
                return {
                    username: "",
                    password: '',
                    showSpinner: false,
                    token: '',
                };
            },
            methods: {
                authLoginAppUser() {
                    let userData = {
                        username: this.username,
                        password: this.password
                    };
    
                    if (this.username && this.password) {
                        axios.post(`http://localhost:8000/api/login`, userData).then(response => {
                            this.logUserInToCometChat(response.data.token)
                        }).catch(error => {
                            alert(error.response.data.message);
                            console.log(error.response.data.message);
                        })
                    } else {
                        alert('Please check your credentials');
                    }
                },
                redirectToRegister() {
                    this.$router.push({name: 'register'});
                }
            }
        };
    </script>

    The authLoginAppUser() method will receive the username and password of a user and use axios to post it to the backend API for authentication. If the credential inputted by the user is correct, the authToken generated for such user during the registration process will be retrieved and returned as part of the JSON response for further usage.

    authLoginAppUser()方法将接收usernamepassword ,并使用axios将其发布到后端API进行身份验证。 如果用户输入的凭据正确,那么将检索并在注册过程中为该用户生成的authToken作为JSON响应的一部分返回,以供进一步使用。

    The returned authToken will now be used to log the user in on CometChat. Add the following method, immediately after the authLoginAppUser for that purpose:

    返回的authToken现在将用于在CometChat上登录用户。 为此,请在authLoginAppUser之后立即添加以下方法:

    logUserInToCometChat(token) {
        this.showSpinner = true;
        CometChat.login(token).then(
            () => {
                this.showSpinner = false;
                console.log("successfully login user");
                this.$router.push({
                    name: 'chat',
                    params: {username: this.username, authenticated: true}
                });
            },
            error => {
                this.showSpinner = false;
                alert("Whops. Something went wrong. This commonly happens when you enter a username that doesn't exist. Check the console for more information");
              this.$router.push({
                  name: 'login',
                  params: {username: this.username, authenticated: true}
              });
                console.log("Login failed with error:", error.code);
            }
        );
    },

    Here, you called the login() method from CometChat SDK and passed the authToken of the user to it as a parameter. Once the user has been authenticated successfully, you will redirect the user to the Chat page by using Vue Router, which handles navigation for the application. Otherwise, a prompt with the appropriate message of why the process failed will be displayed, and the user will be redirected back to the login page.

    在这里,您从CometChat SDK调用了login()方法,并将用户的authToken作为参数传递给它。 成功验证用户身份后,您将使用Vue路由器将用户重定向到“聊天”页面,该路由器处理应用程序的导航。 否则,将显示一个提示,提示有关过程失败的原因的相应消息,并将用户重定向到登录页面。

    聊天视图 ( The chat view )

    Create a new file named Chat.vue within the resources/js/views and update the <template></template> section with the following content:

    resources/js/views创建一个名为Chat.vue的新文件,并使用以下内容更新<template></template>部分:

    // resources/js/views/Chat.vue
    
    <template>
        <div class="booker">
            <nav-bar :name="this.username" :avatar="this.avatar" />
            <div class="chat">
                <div class="container">
                    <div class="msg-header">
                        <div class="active">
                            <h5>#General</h5>
                        </div>
                    </div>
    
                    <div class="chat-page">
                        <div class="msg-inbox">
                            <div class="chats" id="chats">
                                <div class="msg-page" id="msg-page">
    
                                    <div
                                        v-if="loadingMessages"
                                        class="loading-messages-container"
                                    >
                                        <spinner :size="100"/>
                                        <span class="loading-text">
                                Loading Messages
                              </span>
                                    </div>
                                    <div class="text-center img-fluid empty-chat" v-else-if="!groupMessages.length" >
                                        <div class="empty-chat-holder">
                                            <img src="../../assets/empty-state.svg" class="img-res" alt="empty chat image">
                                        </div>
    
                                        <div>
                                            <h2> No new message? </h2>
                                            <h6 class="empty-chat-sub-title">
                                                Send your first message below.
                                            </h6>
                                        </div>
                                    </div>
    
                                    <div v-else>
                                        <div v-for="message in groupMessages" v-bind:key="message.id">
                                            <div class="received-chats" v-if="message.sender.uid !== uid">
                                                <div class="received-chats-img">
                                                    <img v-bind:src="message.sender.avatar" alt="" class="avatar">
                                                </div>
    
                                                <div class="received-msg">
                                                    <div class="received-msg-inbox">
                                                        <p><span>{{ message.sender.uid }}</span><br>{{ message.data.text }}</p>
                                                    </div>
                                                </div>
                                            </div>
    
    
                                            <div class="outgoing-chats" v-else>
                                                <div class="outgoing-chats-msg">
                                                    <p>{{ message.data.text }}</p>
                                                </div>
    
                                                <div class="outgoing-chats-img">
                                                    <img v-bind:src="message.sender.avatar" alt="" class="avatar">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
    
                        <div class="msg-bottom">
                            <form class="message-form" v-on:submit.prevent="sendGroupMessage">
                                <div class="input-group">
                                    <input type="text" class="form-control message-input" placeholder="Type something" v-model="chatMessage" required>
                                    <spinner
                                        v-if="sendingMessage"
                                        class="sending-message-spinner"
                                        :size="30"
                                    />
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>

    The chat view will house all the logic required to interact with the CometChat API to implement the chat functionality, which is the core feature of your application. Here, we will get the details of the logged-in user, implement a method to send and receive messages from a group chat, and also fetch all previous messages sent by a user.

    聊天视图将包含与CometChat API交互以实现聊天功能所需的所有逻辑,这是应用程序的核心功能。 在这里,我们将获取已登录用户的详细信息,实现一种从群聊中发送和接收消息的方法,以及获取用户以前发送的所有消息。

    Here, once a user is authenticated and redirected to the chat page, you will receive the user details and display the unique username, avatar, and also an empty chat page for users who just joined a new group with no previous messages.

    在这里,对用户进行身份验证并将其重定向到聊天页面后,您将收到用户详细信息,并显示唯一的用户名,头像和一个空的聊天页面,供刚刚加入新群组但没有以前消息的用户使用。

    Also included is a form with an input field that will be used by a user to send a message to a group. The form will be processed by a method that will be implemented later in this section named sendGroupMessage().

    还包括带有输入字段的表单,用户将使用该表单将消息发送到组。 表单将通过将在本节稍后部分实现的方法sendGroupMessage()

    Get the logged in user details You will retrieve the details of the currently logged in user by calling a method named getLoggedInUser(). This will return a User object containing all the information related to the logged-in user. Begin by adding this <script> section to this component. Place the contents below within the Chat.vue immediately after the closing tag of the <template> section:

    获取登录的用户详细信息您将通过调用名为getLoggedInUser()的方法来检索当前登录的用户的详细信息。 这将返回一个User对象,其中包含与已登录用户有关的所有信息。 首先将此<script>部分添加到此组件。 将内容放在<template>部分的结束标记之后的Chat.vue

    // resources/js/views/Chat.vue
    
    <script>
        import { CometChat } from "@cometchat-pro/chat";
        import NavBar from "../components/NavBar.vue";
        import Spinner from "../components/Spinner.vue";
    
        export default {
            name: "home",
            components: {
                NavBar,
                Spinner
            },
            data() {
                return {
                    username: "",
                    avatar: "",
                    uid: "",
                    sendingMessage: false,
                    chatMessage: "",
                    loggingOut: false,
                    groupMessages: [],
                    loadingMessages: false
                };
            },
            created() {
                this.getLoggedInUser();
            },
            methods: {
                getLoggedInUser() {
                    CometChat.getLoggedinUser().then(
                        user => {
                            this.username = user.name;
                            this.avatar = user.avatar;
                            this.uid = user.uid;
                        },
                        error => {
                            this.$router.push({
                                name: "homepage"
                            });
                            console.log(error);
                        }
                    );
                },
            }
        };
    </script>

    Once the details of the currently authenticated user are retrieved, the name, the avatar (if any), and unique user Id will also be updated. Otherwise, the user will be redirected to the login page

    一旦检索到当前已认证用户的详细信息,名称,头像(如果有)和唯一用户ID也将被更新。 否则,用户将被重定向到登录页面

    Send new messages Add the method below to implement the logic to send a new message to CometChat server during a group chat session:

    发送新消息添加以下方法,以实现在群聊会话期间向CometChat服务器发送新消息的逻辑:

    sendGroupMessage() {
        this.sendingMessage = true;
        var receiverID = process.env.MIX_COMMETCHAT_GUID;
        var messageText = this.chatMessage;
        var receiverType = CometChat.RECEIVER_TYPE.GROUP;
    
        var textMessage = new CometChat.TextMessage(
            receiverID,
            messageText,
            receiverType
        );
    
        CometChat.sendMessage(textMessage).then(
            message => {
                console.log("Message sent successfully:", message);
                this.chatMessage = "";
                this.sendingMessage = false;
                this.$nextTick(() => {
                    this.scrollToBottom()
                })
            },
            error => {
                console.log("Message sending failed with error:", error);
            }
        );
    }

    Here, you called the sendMessage() method and passed a constructed TextMessage() to it. The TextMessage class constructor takes the GUID, messageText and receiverType as parameters. Receive incoming messages and Fetch previous messages Lastly, add the following method to receive real-time incoming messages posted to a group by its participants:

    在这里,您调用了sendMessage()方法并将一个构造的TextMessage()传递给它。 TextMessage类的构造函数将GUIDmessageTextreceiverType作为参数。 接收传入消息并获取以前的消息最后,添加以下方法以接收其参与者发布到组的实时传入消息:

    export default {
        ...
        mounted() {
            this.loadingMessages = true
            var listenerID = "UNIQUE_LISTENER_ID";
    
            const messagesRequest = new CometChat.MessagesRequestBuilder()
                .setLimit(100)
                .build()
            messagesRequest.fetchPrevious().then(
                messages => {
                    console.log("Message list fetched:", messages);
                    console.log("this.groupMessages", this.groupMessages)
                    this.groupMessages = [
                        ...this.groupMessages,
                        ...messages
                    ];
                    this.loadingMessages = false
                    this.$nextTick(() => {
                        this.scrollToBottom();
                    })
                },
                error => {
                    console.log("Message fetching failed with error:", error);
                }
            );
    
            CometChat.addMessageListener(
                listenerID,
                new CometChat.MessageListener({
                    onTextMessageReceived: textMessage => {
                        console.log("Text message received successfully", textMessage);
                        // Handle text message
                        console.log(this.groupMessages)
                        this.groupMessages = [
                            ...this.groupMessages,
                            textMessage
                        ];
                        this.loadingMessages = false
                        this.$nextTick(() => {
                            this.scrollToBottom();
                        })
                    }
                })
            );
        }
    };

    An event listener that takes a unique listenerID as a parameter was registered to listen for messages when your app is running. Lastly, once a user logs in, the MessagesRequestBuilder will be used to fetch any previous messages from the group and update the view with it.

    已注册一个具有唯一listenerID作为参数的事件侦听器,以在您的应用程序运行时侦听消息。 最后,用户登录后,将使用MessagesRequestBuilder来从组中获取任何先前的消息并使用该视图更新视图。

    更新路由器 ( Update the router )

    Now, in order to render a component for each given path, you will update the generated router file within the project. Open the router file located in .resources/js/routes.js and replace its content with the following:

    现在,为了渲染每个给定路径的组件,您将更新项目中生成的路由器文件。 打开位于.resources/js/routes.js的路由器文件,并将其内容替换为以下内容:

    // resources/js/routes.js
    
    import Vue from 'vue';
    import VueRouter from "vue-router";
    import Login from './views/Login';
    import Register from "./views/Register";
    import Chat from "./views/Chat";
    
    Vue.use(VueRouter);
    
    export default new VueRouter({
        mode: 'history',
        routes: [
            {
                path: '/',
                name: 'homepage',
                redirect: 'login'
            },
            {
                path: '/login',
                name: 'login',
                component: Login
            },
            {
                path: '/register',
                name: 'register',
                component: Register
            },
            {
                path: '/chat',
                name: 'chat',
                component: Chat,
            },
            {
                path: '*',
                name: 'Not found',
                redirect: 'login'
            }
        ]
    })

    You successfully map each route within your application to the respective component that will handle the logic. This is a basic format of configuring Vue Router for a Vue.js application.

    您已成功将应用程序中的每个路由映射到将处理逻辑的相应组件。 这是为Vue.js应用程序配置Vue路由器的基本格式。

    配置入口点 ( Configure the entry point )

    Navigate to resources/js/app.js and confirm that its content is the same as what you have below. If otherwise, feel free to update its content with this:

    导航到resources/js/app.js并确认其内容与下面的内容相同。 否则,请随时使用以下内容更新其内容:

    // resources/js/app.js
    
    require('./bootstrap');
    
    window.Vue = require('vue');
    import VueRouter from "vue-router";
    import App from './App.vue';
    import routes from "./routes";
    
    
    Vue.use(VueRouter);
    
    const app = new Vue({
        el: '#app',
        router: routes,
        components: {App}
    });

    Here, you imported Vue, Vue Router library, and the routes file. You then proceeded to create a Vue instance and pass both the router and application components to it.

    在这里,您导入了Vue,Vue路由器库和路由文件。 然后,您继续创建Vue实例,并将路由器和应用程序组件都传递给它。

    测试应用 ( Test the application )

    If you have followed the tutorial up until now, well done! You have successfully built a group chat application with authentication using Laravel and Vue.js. To test all the implementation and be certain that it works as designed, open two different terminals, and ensure that you are within the project’s directory. Run the backend application from one of the terminals using the following command:

    如果您到目前为止一直在学习本教程,那就做得很好! 您已经使用Laravel和Vue.js成功地构建了带有身份验证的群聊应用程序。 要测试所有实现并确定它是否按设计工作,请打开两个不同的终端,并确保您位于项目目录中。 使用以下命令从终端之一运行后端应用程序:

    php artisan serve

    This will start the application on the default port 8000. Next, to start the frontend application, use npm as shown here:

    这将在默认端口8000上启动应用程序。接下来,要启动前端应用程序,请使用npm ,如下所示:

    npm run watch

    The preceding command will compile all the Vue.js project and continue running the app in watch mode for changes to any relevant files. Now, navigate to http://localhost:8000, to view the application in your browser:

    前面的命令将编译所有Vue.js项目,并继续以监视模式运行该应用程序以更改任何相关文件。 现在,浏览至http:// localhost:8000 ,以在浏览器中查看该应用程序:

    Register a user Click on the Register link to register a new user.

    注册用户单击“ 注册”链接以注册新用户。

    Once the registration process is successful, the user will both be created within your application and also on CometChat. You can log in into your CometChat dashboard and click on the Users tab to view the newly created users. Login and start a chat session Immediately after registration, you will be redirected to the Login page. Input the appropriate credential and start a chat session:

    一旦注册过程成功,将在您的应用程序内以及CometChat上都创建用户。 您可以登录到CometChat仪表板 ,然后单击“ 用户”选项卡以查看新创建的用户。 登录并开始聊天会话注册后,您将立即重定向到“登录”页面。 输入适当的凭据并开始聊天会话:

    结论 ( Conclusion )

    In this tutorial, you built a chat application using Laravel and Vue.js. I hope that this gives you a proper understanding of how seamless it is to combine these tools to build an awesome chat experience. As you must have noticed, this application can actually be improved on, and I will leave that for you to enhance.

    在本教程中,您使用Laravel和Vue.js构建了一个聊天应用程序。 我希望这能使您正确地理解将这些工具组合在一起以建立令人赞叹的聊天体验的无缝性。 正如您必须已经注意到的那样,实际上可以对该应用程序进行改进,我将其留给您进行增强。

    You can also clone the completed app from Github if you want to have a reference.

    如果您想获得参考,也可以从Github克隆完成的应用程序。

    翻译自: https://scotch.io/tutorials/build-a-chat-app-with-laravel-and-vue

    laravel 使用vue

    展开全文
  • 前提:确保你的电脑安装了 node 和 npm 1、安装 laravel5.7: composer create-project laravel/...2、laravel 自带 vue,所以只要在根目录下执行: npm install —— 执行该命令会自动安装 package.j...

    前提:确保你的电脑安装了 node 和 npm

     

    1、安装 laravel5.7:

    composer create-project laravel/laravel --prefer-dist laravel "5.7.*"

     

    2、laravel 自带 vue,所以只要在根目录下执行:

    npm install

    —— 执行该命令会自动安装 package.json 里面指定的文件。 

     

    3、修改 route/web.php:(这步其实是把默认的 welcome 改成了 index)

    // 把根目录指向 index.blade.php
    Route::get('/', function () {
        return view('index');
    });

    并且将 resources/views/index.blade.php 内容设置为:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel</title>
    <link href="/css/app.css" rel="stylesheet">

    </head>
    <body>
    <div id="app">
    <example></example>
    </div>
    </body>
    <script src="{{ mix('js/app.js') }}"></script>
    </html>

    —— 其实这里的 index.blade.php,就是使用 cli 构建出来的 index.html 一样的。域名指向了这个 html,然后这个 html 挂载了 app.js,就可以跟 vue 交互了。剩下的事情就是单页面的 vue 怎么用 api 和 后端交互的问题了。没有任何的区别。

      

    4、修改 app.js 的模板设置:

    //
    Vue.component('example-component', require('./components/ExampleComponent.vue').default);
    // 修改为:
    Vue.component('example', require('./components/ExampleComponent.vue').default);

     

    5、执行run,看下laravel 的画面是否出现:

    npm run dev  // 或者 npm run watch

     

    6、引入 elementUI:

    // 安装,完成后会在 node_modules 下多出 element-ui的文件夹
    npm i element-ui -S
    // 引入,在 resources/assets/js/app.js 文件中加入 import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(ElementUI);

     

    7、测试elementUI 的效果:

    修改ExampleComponent.vue文件 在文件中随便加入element组件:

    <template>
        <div class="container">
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <div class="panel panel-default">
                        <div class="panel-heading">Example Component</div>
    
                        <div class="panel-body">
                            I'm an example component!
                        </div>
                        <el-select v-model="value" placeholder="请选择">
                            <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                </div>
            </div>
        </div>
    </template>
    
    <script>
        export default {
            data() {
                return {
                    options: [{
                        value: '选项1',
                        label: '黄金糕'
                    }, {
                        value: '选项2',
                        label: '双皮奶'
                    }, {
                        value: '选项3',
                        label: '蚵仔煎'
                    }, {
                        value: '选项4',
                        label: '龙须面'
                    }, {
                        value: '选项5',
                        label: '北京烤鸭'
                    }],
                    value: ''
                }
            }
        }
    </script>

    —— 执行 npm run dev 或者 npm run watch 即可查看效果

     

    8、安装 vue-rouute:

    npm install vue-router --save-dev

     

    9、在 resource/js 下创建 route.js 和 App.vue

    route.js 添加内容:

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    Vue.use(VueRouter);
    
    export default new VueRouter({
        saveScrollPosition: true,
        routes: [
            {
                name: "index",
                path: '/',
                component: resolve => void(require(['./components/ExampleComponent.vue'], resolve))
            },
        ]
    });

    App.vue添加内容:

    <template>
        <div>
            <router-view></router-view>
        </div>
    </template>
    <script scoped>
    
        export default {
            data(){
                return {}
            },
            components: {
    
            },
            computed: {},
            methods: {
    
            },
            mounted() {
            },
        }
    </script>

     

    10、app.js 里面引入 route.js 和 App.vue

    /**
     * xxxxxxxx
     */
    
    require('./bootstrap');
    
    window.Vue = require('vue');
    
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    
    import App from './App.vue';          //添加的内容
    import router from './router.js';     //添加的内容
    
    Vue.use(ElementUI);
    
    /**
     * xxxxxxxx
     */
    
    // const files = require.context('./', true, /\.vue$/i)
    // files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))
    // Vue.component('example-component', require('./components/ExampleComponent.vue').default);
    Vue.component('example', require('./components/ExampleComponent.vue').default);
    
    /**
     * xxxxxxxx
     */
    
    const app = new Vue({
        el: '#app',
        router,               //添加的内容
        render:h => h(App)    //添加的内容
    });

     

    11、测试路由:

     添加一个path 为 /test 的路由,并且在 component 里面创建 TestComponent.vue 组件并加入以下内容:

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    Vue.use(VueRouter);
    
    export default new VueRouter({
        saveScrollPosition: true,
        routes: [
            {
                name: "index",
                path: '/',
                component: resolve => void(require(['./components/ExampleComponent.vue'], resolve))
            },
            {
                name: "test",
                path: '/test',
                component: resolve => void(require(['./components/TestComponent.vue'], resolve))
            },
        ]
    });

    —— npm run dev ,然后访问 http://laravel.com/#/test进行访问,可得到最新数据。

     

    ———— 自此,laravel 下安装 vue ,并安装路由和

     

    //关于 npm install 的说明:

    --save 表示开发和线上环境都得有这个库。-- save-dev是只有开发环境才需要,比如 webpack 这个包,就只有开发环境才需要。

    对应 package.json 就是 devDependencies 和 dependencies 的配置差别。dependencies里面的开发和线上都会有。

     => 但是: 因为 vue 最后并不需要 build 上线,而是通过 laravel-mix 自动同步到了public 下,所有我觉得与 laravel 的混合使用,是没有开发环境和上线的区别的。

     

     

     

    ———— 文件介绍 ————

    // routes\web.php

    这个文件是Laravel的路由文件,Vue开发中用一句指向入口文件

    // resources\views

     laravel的视图目录,Vue开发中这里只有一个文件,作为入口文件。

    // webpack.mix.js

    这个文件是laravel-mix的配置文件,其中配置了 vue 编写和 css 的位置:

    mix.js('resources/js/app.js', 'public/js')
       .sass('resources/sass/app.scss', 'public/css');

     // resources/js/app.js

    这个文件是Vue的入口文件,所有的组件都会在这里注册。

    // resources/js/components

    这个目录下存放的是Vue单文件组件。

     // resources/sass

    存放 vue 的css 文件

     

     

     

     

    —————— 常用命令 ——————

     

    // 安装 package.json 指定的文件
    npm install
    //
    编译前端文件,会执行 webpack.mix.js 文件配置,将编译好的资源放到 public 下。 npm run dev // 自动检测前端文件变化并实时编译。 npm run watch

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    ———— 占位符

    转载于:https://www.cnblogs.com/windyet/articles/10160355.html

    展开全文
  • 我们可以看一下app.js的代码,发现他是引入了vue,然后注册了一个组件,也就时Example.vue , Example.vue 中输出两句话,这是一个完整的组件,我们可以直接使用。 我们找到resources\views\welcome.blade.php 文件...
  • Laravel使用Vue组件开发进行收藏文章

    千次阅读 2018-04-16 15:49:49
    使用Vue组件开发进行收藏文章 前提: php : 7.1.3 laravel/framework: 5.6.* vue 2.5.7 先贴一下前端需要的工具package.json问文件,可能存在不需要的 { "private": true, "scripts&...
  • 1)首先要安装 gulp ... 2)编辑js 默认 laravel 里有一个/resources/assets/js/app.js 这个 gulp 要编译文件,gulp 将/resources/assets/js/app.js 编译成 /public/js/app.js 文件,/publi...
  • Vue创建的是spa(单页面)项目,一个项目仅在一个web页面中完成,也可以理解为一个项目就是一个vue实例,也就是通过new Vue()语句创建的对象。然后把这个实例放在HTML中显示出来,这就是挂载 new Vue({ // el是实例挂载...
  • 原文博客地址https://xgs888.top/post/view?id=89... 前端使用的是vue.js后端使用的是laravel获取到接口的数据, vue-bootstrap-pagination所需要的数据格式记录一下; &lt;divclass='col-lg-5'&gt; ...
  • 组件注册时需在引入组件后面添加.default
  • Laravel-Vue SPA Laravel-Vue SPA入门套件。 产品特点 Laravel 8 Vue + VueRouter + Vuex + VueI18n + ESlint 具有动态导入和自定义布局的页面 登录,注册,电子邮件验证和密码重置 使用JWT进行身份验证 社交名流...
  • 该软件包允许使用Vue使用Laravel应用程序轻松设置本地化。 它基于 安装 $ yarn add laravel-vue-lang 随着Laravel Mix扩展 该软件包附带Laravel Mix扩展。 您可以包含它并在Mix上调用.lang() 。 如果由于某种原因您...
  • laravel-vue-admin参考了许多类似的项目,使用起来都很方便。例如,Larave-Admin,FastAdmin,可以快速开发后台。而Laravel-vue -admin也主要是因我个人开发习惯才产生的想法。 Laravel-vue-Admin中项目文档 编码云...
  • laravel-vue-good-table ... laravel-vue-good-table使用Vue组件laravel-vue-good-table 。 控制器: namespace App \ Http \ Controllers ; use LaravelVueGoodTable \ InteractsWithVueGoodTable ; use Laravel
  • Laravel试图通过减轻大多数Web项目中使用的常见任务来减轻开发工作的痛苦,例如: 。 。 用于和存储的多个后端。 富有表现力,直观的 。 数据库不可知。 。 。 Laravel易于访问,但功能强大,可提供大型,...
  • Laravel减轻了许多Web项目中使用的常见任务,从而减轻了开发过程中的痛苦,例如: 。 。 用于和存储的多个后端。 富有表现力,直观的 。 数据库不可知。 。 。 Laravel易于访问,功能强大,并提供大型,...
  • Laravel-Vue-Spa-样板 入门 介绍 这是具有JWT身份验证的Laravel(5.5)Vue js SPA(单页应用程序)样板项目。 安装 在开始之前,请检查官方的laravel安装指南以了解服务器要求。 克隆存储库 git clone ...
  • Laravel Vue模板通过减轻许多Web项目中使用的常见任务来减轻开发工作的痛苦,例如: 。 。 用于和存储的多个后端。 富有表现力,直观的 。 数据库不可知。 。 。 Laravel Vue模板易于访问,功能强大,并...
  • laravel_vue_test 使用laravelvue.js测试spa
  • 使用Laravel 8和Vue 3创建一个电子商务网站。 产品特点 Laravel 8 Vue 3 VueX状态管理 付款条带 使用AirBnB规则集的ESLint代码 合成API 动画制作 SonarCloud代码质量扫描仪在所有请求请求上的集成 Laravel与...
  • Laravel 7中的高级电子商务网站 设置视频: : 演示视频: 完整教程: 特征 : ======前端======= 响应式布局 购物车,愿望清单,产品评论 优惠券和折扣 ...使用unisharp laravel文件管理器的媒体管

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 821
精华内容 328
关键字:

laravel使用vue

vue 订阅