目录
在构建个人博客系统时,文章发布和编辑功能是非常重要的一部分。这个功能不仅可以让我们添加新的文章,还可以让我们修改现有的文章。在这篇博客中,我们将使用 Vue 3 作为前端框架,Go 作为后端语言,MySQL 作为数据库,来实现这个功能。
前端部分
创建文章发布和编辑页面
首先,我们需要在 src/components
目录下创建一个新的组件 ArticleEditor.vue
,用于文章的发布和编辑。
<template>
<div>
<input type="text" v-model="article.title" placeholder="Title" />
<textarea v-model="article.content" placeholder="Content"></textarea>
<button @click="submit">Submit</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
article: {
title: '',
content: '',
},
};
},
methods: {
async submit() {
const res = await axios.post('http://localhost:8080/articles', this.article);
this.$router.push(`/article/${res.data.id}`);
},
},
};
</script>
在这个组件中,我们首先定义了一个 article
对象,用于绑定输入框和文本区域的值。然后我们定义了一个 submit
方法,这个方法会在点击 "Submit" 按钮时调用。在这个方法中,我们使用 axios 向后端发送 POST 请求提交文章数据,然后跳转到新文章的详情页。
实现富文本编辑
对于富文本编辑,我们可以使用一个名为 quill
的富文本编辑器库。首先,我们需要在项目中安装这个库:
npm install quill
然后,我们可以在 ArticleEditor.vue
组件中使用这个库:
<template>
<div>
<input type="text" v-model="article.title" placeholder="Title" />
<div id="editor"></div>
<button @click="submit">Submit</button>
</div>
</template>
<script>
import axios from 'axios';
import Quill from 'quill';
export default {
data() {
return {
article: {
title: '',
content: '',
},
editor: null,
};
},
mounted() {
this.editor = new Quill('#editor');
},
methods: {
async submit() {
this.article.content = this.editor.getContents();
const res = await axios.post('http://localhost:8080/articles', this.article);
this.$router.push(`/article/${res.data.id}`);
},
},
};
</script>
在这个组件中,我们首先在 mounted
钩子函数中初始化 quill
编辑器。然后在 submit
方法中,我们从编辑器中获取内容并赋值给 article.content
。
实现文件上传
对于文件上传,我们可以使用 HTML 的 input
元素和 axios 库。首先,我们需要在 ArticleEditor.vue
组件的模板中添加一个 input
元素:
<script>
// other code
export default {
// other code
methods: {
// other methods
async upload(e) {
const file = e.target.files[0];
const formData = new FormData();
formData.append('file', file);
const res = await axios.post('http://localhost:8080/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
this.article.image = res.data.url;
},
},
};
</script>
在这个方法中,我们首先从事件对象中获取选中的文件,然后创建一个 FormData
对象并将文件添加到其中。然后我们使用 axios 向后端发送 POST 请求上传文件。最后,我们将上传的文件的 URL 赋值给 article.image
。
后端部分
实现文章发布和编辑接口
在后端,我们需要在 main.go
文件中实现文章发布和编辑的接口。首先,我们需要在 main
函数中添加两个新的路由:
func main() {
// other code
r.POST("/articles", createArticle)
r.PUT("/articles/:id", updateArticle)
// other code
}
然后,我们需要实现 createArticle
和 updateArticle
函数:
func createArticle(c *gin.Context) {
// parse and validate the request body
var article Article
if err := c.ShouldBindJSON(&article); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// insert the article into the database
res, err := db.Exec("INSERT INTO articles (title, content) VALUES (?, ?)", article.Title, article.Content)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// return the article ID
id, err := res.LastInsertId()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"id": id})
}
func updateArticle(c *gin.Context) {
// get the article ID from the URL
id := c.Param("id")
// parse and validate the request body
var article Article
if err := c.ShouldBindJSON(&article); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// update the article in the database
_, err := db.Exec("UPDATE articles SET title = ?, content = ? WHERE id = ?", article.Title, article.Content, id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// return the article ID
c.JSON(http.StatusOK, gin.H{"id": id})
}
在这两个函数中,我们首先从请求体中解析并验证文章数据,然后将文章数据插入到数据库中(createArticle
函数)或更新数据库中的文章数据(updateArticle
函数)。最后,我们返回新创建或更新的文章的 ID。
实现文件上传接口
为了实现文件上传,我们需要在 main
函数中添加一个新的路由:
func main() {
// other code
r.POST("/upload", upload)
// other code
}
然后,我们需要实现 upload
函数:
func upload(c *gin.Context) {
// get the file from the request
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// save the file
path := fmt.Sprintf("./uploads/%s", file.Filename)
if err := c.SaveUploadedFile(file, path); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// return the file URL
c.JSON(http.StatusOK, gin.H{"url": fmt.Sprintf("http://localhost:8080/uploads/%s", file.Filename)})
}
在这个函数中,我们首先从请求中获取文件,然后将文件保存到 ./uploads
目录下。最后,我们返回文件的 URL。
以上就是使用 Vue 3、Go 和 MySQL 实现文章发布和编辑功能的全部内容。如果你有任何疑问,欢迎在评论区留言。