初始化项目
composer create-project laravel/laravel comments
创建数据库,配置.env
文件。我这里的数据库是comments
使用系统自带的验证程序。
php artisan make:auth
php artisan migrate
使用npm命令安装依赖和tailwindcss
cnpm install tailwindcss --save-dev
cnpm install
本教程涉及到的代码我都将上传至:
https://github.com/leienshu/comments
构建组件结构
先使用下面的命令来观察sass文件或者js文件的一些变动情况。
npm run watch
清除home.blade.php
文件中@section 和 @endsection 部分的内容。

对了,上面的Laravel标题在env文件中可以改成Comments Demo。
好了,现在我们进入 resources/js/components 目录,新建一个新的Vue文件,名字叫:CommentsManager.vue ,具体内容如下:
<template>
<div>
<h1>Hello World</h1>
</div>
</template>
<script>
export default {
data: function() {
return {
}
},
}
</script>
在 app.js 文件中注册上面新建的 vue 文件。把之前的example-component注释掉。
Vue.component('comments-manager', require('./components/CommentsManager.vue').default);
在 home.blade.php 文件的section部分添加下面的模板。
<comments-manager></comments-manager>

用户界面有点丑,不过我们继续干吧。
显示评论
在CommentsManager的data属性里,我们增加一些评论数据。如下:
return {
comments: [
{
id: 1,
body: "咋整的呢?",
edited: false,
created_at: new Date().toLocaleString(),
author: {
id: 1,
name: '雷经纬',
}
}
]
}
现在我们就有了一些数据可以使用,我们可以开始在页面上显示它。但是,现在虽然可以将所有逻辑保存在CommentsManager组件中,但我们最终必须编写一些奇怪的方法来解析每个注释的详细信息。所以,我们最好为每个评论制作另一个组件。
在 comments-manager.vue 相同目录下,再新建一个 CommentItem.vue 文件。
<template>
<div>
</div>
</template>
<script>
export default {
data: function() {
return {
}
},
}
</script>
现在,让我们通过一个评论属性,包含所有评论的数据,然后将其添加到模板中。
<template>
<div>
<div>
<p>{
{comment.body}}</p>
</div>
<div>
<p>{
{comment.author.name}} <span>--</span>{
{ comment.created_at}}</p>
</div>
</div>
</template>
<script>
export default {
props: {
comment: {
required: true,
type: Object,
}
},
data: function() {
return {
}
},
}
</script>
现在进入 CommentsManager.vue 文件来注册CommentItem。
<template>
<div>
<div>
<comment v-for="comment in comments"
:key="comment.id"
:comment="comment">
</comment>
</div>
</div>
</template>
<script>
import comment from './CommentItem'
export default {
components: {
comment
},
data: function() {
return {
comments: [
{
id: 1,
body: "咋整的呢?",
edited: false,
created_at: new Date().toLocaleString(),
author: {
id: 1,
name: '雷经纬',