VUE3+GO personal blog system: realization of article list page and detail page

Table of contents

Configuration Environment

Project initialization

Build an article list page

Build an article details page

configure routing

implement the backend

Connect to MySQL database


When building a personal blog system, the article list page and the details page are two indispensable interfaces. The article list page is used to display the brief information of all articles, and the detail page is used to display the full text of the articles. In this blog, we will use Vue 3 as the front-end framework, Go as the back-end language, and MySQL as the database to build these two pages.

Configuration Environment

First, make sure your development environment has the following software installed:

  • Node.js and npm
  • Go
  • MySQL
  • View CLI 4

You can verify it is installed by checking the version:

node -v
npm -v
go version
mysql --version
vue --version

Project initialization

First, we need to create a new Vue 3 project via the Vue CLI. Run the following command in a terminal:

vue create my-blog

Then select "Manually select features", select "Choose Vue version", "Babel", "Router", "Linter / Formatter", and select Vue 3 in "Choose Vue version".

After the project is created, enter the project directory:

cd my-blog

Build an article list page

First, we need to create a new component in src/componentsthe directory ArticleList.vue. This component will be responsible for fetching and displaying the list of articles.

<template>
  <div>
    <div v-for="article in articles" :key="article.id">
      <h2>{
   
   { article.title }}</h2>
      <p>{
   
   { article.abstract }}</p>
      <router-link :to="`/article/${article.id}`">Read More</router-link>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      articles: [],
    };
  },
  async created() {
    const res = await axios.get('http://localhost:8080/articles');
    this.articles = res.data;
  },
};
</script>

In this component, we first define an articlesarray to store article data. Then after the component is created, we use axios to send a GET request to the backend to get the list of articles, and assign the obtained data to articles.

Build an article details page

Again, we need to create a new component under src/componentsthe directory ArticleDetail.vue. This component will be responsible for fetching and displaying article details.

<template>
  <div>
    <h1>{
   
   { article.title }}</h1>
    <p>{
   
   { article.content }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      article: {},
    };
  },
  async created() {
    const id = this.$route.params.id;
    const res = await axios.get(`http://localhost:8080/articles/${id}`);
    this.article = res.data;
  },
};
</script>

The structure of this component is ArticleList.vuesimilar to , the difference is that we get the parameters of the current route after the component is created id, and then use this to send a GET request idto the backend to get article details.

configure routing

Then, we need to configure the routes in src/router/index.jsthe file :

import { createRouter, createWebHistory } from 'vue-router';
import ArticleList from '../components/ArticleList.vue';
import ArticleDetail from '../components/ArticleDetail.vue';

const routes = [
  {
    path: '/',
    name: 'ArticleList',
    component: ArticleList,
  },
  {
    path: '/article/:id',
    name: 'ArticleDetail',
    component: ArticleDetail,
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

In this config file, we define the path for ArticleListthe component '/'and the path for ArticleDetailthe component '/article/:id'.

implement the backend

Next, we need to implement the backend service. In main.gothe file , we first define two structures Articleand Articlesfor storing article data. Then we define a handler function getArticlesthat handles the GET request and returns all the article data. Similarly, we also define a processing function getArticlefor processing the GET request with the id parameter and returning the corresponding article data.

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type Article struct {
	ID      int    `json:"id"`
	Title   string `json:"title"`
	Content string `json:"content"`
}

type Articles []Article

func getArticles(c *gin.Context) {
	articles := Articles{
		Article{1, "First Article", "This is the content of the first article."},
		Article{2, "Second Article", "This is the content of the second article."},
	}

	c.JSON(http.StatusOK, gin.H{"data": articles})
}

func getArticle(c *gin.Context) {
	id := c.Param("id")
	article := Article{1, "First Article", "This is the content of the first article."}

	if id == "1" {
		c.JSON(http.StatusOK, gin.H{"data": article})
	} else {
		c.JSON(http.StatusNotFound, gin.H{"data": "Not Found"})
	}
}

func main() {
	r := gin.Default()

	r.GET("/articles", getArticles)
	r.GET("/articles/:id", getArticle)

	r.Run(":8080")
}

Connect to MySQL database

In order to get real data from the database, we need to use database/sqlthe package to connect to the MySQL database. First, we need to add a new database connection in mainthe function :

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	// other imports
)

func main() {
	db, err := sql.Open("mysql", "user:password@/dbname")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// other code
}

Then, we need getArticlesto getArticleuse this database connection in the and functions to fetch data. Because this task involves database operations, I cannot provide the complete code here. But the basic idea is:

  1. Use db.Querythe or db.QueryRowfunction to execute SQL queries.
  2. Use rows.Scanthe function to store the query results in a structure.

I hope this blog helps you implement article list and detail pages in Vue 3 and Go. If you have any questions, please leave a message in the comment area.

おすすめ

転載: blog.csdn.net/m0_68036862/article/details/131156736