首页 > 文章列表 > VUE3入门实例:构建一个简单的论坛应用程序

VUE3入门实例:构建一个简单的论坛应用程序

vue 论坛 应用程序
330 2023-06-15

VUE3入门实例:构建一个简单的论坛应用程序

在移动互联网时代,论坛是一个非常普遍的社区形式,为人们提供了一个交流的平台,为了帮助初学者更好的理解VUE3的用法,本篇文章将带领大家创建一个简单的论坛应用程序。

  1. 创建Vue3项目

首先,我们需要在本地环境中安装Vue CLI。打开命令行,然后输入以下命令:

npm install -g @vue/cli

当安装完成后,创建一个基于VUE 3.0的项目:

vue create vue-forum

进入该目录,运行以下命令启动项目:

cd vue-forum
npm run serve

现在,你可以在浏览器中访问 http://localhost:8080 并看到基于Vue的欢迎页面。

  1. 安装必需的插件

我们需要安装一些必需的插件来搭建我们的论坛应用程序:

npm install vue-router axios

Vue-router是用于管理应用程序路由的npm包,Axios是一个用于处理Web服务请求的强大的JavaScript库。

  1. 配置Vue-router

接下来,我们需要在项目中配置Vue Router。在src目录下新建一个名为router.js的文件,并添加以下代码:

import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import Forum from './views/Forum.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/forum',
    name: 'forum',
    component: Forum
  }
]

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

export default router

该代码片段定义了路由的路径、名称、以及相应的组件。现在,我们需要将该组件导入到App.vue中。打开App.vue,将以下代码添加到template标签中:

<router-view></router-view>

该代码片段是Vue Router的出口,这里显示了我们的组件。

  1. 创建组件

现在,我们可以创建两个用于路由路径的组件,即Home.vue和Forum.vue。作为一个简单的论坛应用程序,Home.vue 可以作为访问我们的主页。而Forum.vue将作为进入论坛的页面。

以上述代码为模板,我们分别创建两个组件,并将它们在router.js中注册。现在,我们可以在http://localhost:8080 上看到Home.vue的欢迎页面,也可以通过访问http://localhost:8080/forum 访问我们的论坛页面了。

  1. 获取数据

我们的论坛应用程序需要从Web服务中获取一些数据,如获取所有的帖子和评论。为了达到这个目的,我们将使用可以处理Web服务请求的Axios。

Forum.vue文件中添加以下代码来获取帖子列表:

<template>
  <div class="forum">
    <h2>论坛</h2>

    <ul>
      <li v-for="post in posts" :key="post.id">
        <h3>{{ post.title }}</h3>
        <p>{{ post.body }}</p>
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      posts: []
    }
  },

  created() {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        this.posts = response.data
      })
      .catch(error => {
        console.log(error)
      })
  }
}
</script>

<style>
h3 {
  margin-bottom: 0;
}
</style>

以上代码会在组件加载时发起一个HTTP GET请求,以获取帖子清单。我们使用了一个与jsonplaceholder(在线测试restapi)相连的公共JSON API。

  1. 组装数据

Forum.vue中,我们只要根据用户请求的帖子Id,在另一个页面中显示该帖子的详细内容。为了实现这一目的,我们需要获取评论清单,以及对信息进行组装。在组件中导入这些评论,并将它们添加到帖子对象中。最后,我们根据帖子ID显示详细信息。

<template>
  <div class="forum">
    <h2>Forum</h2>

    <ul>
      <li v-for="post in posts" :key="post.id" @click="showPostDetails(post.id)">
        <h3>{{ post.title }}</h3>
        <p>{{ post.body }}</p>
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      posts: [],
      comments: []
    }
  },

  created() {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        this.posts = response.data
      })
      .catch(error => {
        console.log(error)
      })
  },

  methods: {
    showPostDetails(id) {
      axios.get(`https://jsonplaceholder.typicode.com/comments?postId=${id}`)
        .then(response => {
          this.comments = response.data
          const post = this.posts.find(post => post.id === id)
          post.comments = this.comments
          this.$router.push({ name: 'post', params: { id: id } })
        })
        .catch(error => {
          console.log(error)
        })
    }
  }
}
</script>

<style>
h3 {
  margin-bottom: 0;
}
</style>
  1. 显示帖子

现在,我们拥有了组装后的数据,并将其存储在帖子里。我们还需要一些代码来显示该帖子的详细内容。在我们的程序中,这将通过创建一个名为“Post.vue”的组件来完成。添加以下代码:

<template>
  <div class="post">
    <h2>{{ post.title }}</h2>

    <p>{{ post.body }}</p>

    <h3>Comments:</h3>
    <ul>
      <li v-for="comment in post.comments" :key="comment.id">
        <div>{{ comment.name }}</div>
        <div>{{ comment.email }}</div>
        <div>{{ comment.body }}</div>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      post: {}
    }
  },

  created() {
    const postId = this.$route.params.id
    const post = this.$root.posts.find(post => post.id === Number(postId))
    this.post = post
  }
}
</script>

<style>
h2 {
  margin-bottom: 0;
}

h3 {
  margin-top: 2rem;
  margin-bottom: 0;
}
</style>

以上代码将获取路由参数中的帖子ID,并从our program root的对象中获取该帖子的详细信息。

  1. 最终代码

现在,我们已经成功地创建了一个简单的论坛应用程序!以下是我们的“router.js”文件、以及“Home.vue”、“Forum.vue”和“Post.vue”组件的最终代码。

router.js

import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import Forum from './views/Forum.vue'
import Post from './views/Post.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/forum',
    name: 'forum',
    component: Forum
  },
  {
    path: '/forum/:id',
    name: 'post',
    component: Post
  }
]

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

export default router

Home.vue

<template>
  <div class="home">
    <h1>Welcome to our forum!</h1>
  </div>
</template>

<style>
h1 {
  text-align: center;
}
</style>

Forum.vue

<template>
  <div class="forum">
    <h2>Forum</h2>

    <ul>
      <li v-for="post in posts" :key="post.id" @click="showPostDetails(post.id)">
        <h3>{{ post.title }}</h3>
        <p>{{ post.body }}</p>
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      posts: [],
      comments: []
    }
  },

  created() {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        this.posts = response.data
      })
      .catch(error => {
        console.log(error)
      })
  },

  methods: {
    showPostDetails(id) {
      axios.get(`https://jsonplaceholder.typicode.com/comments?postId=${id}`)
        .then(response => {
          this.comments = response.data
          const post = this.posts.find(post => post.id === id)
          post.comments = this.comments
          this.$router.push({ name: 'post', params: { id: id } })
        })
        .catch(error => {
          console.log(error)
        })
    }
  }
}
</script>

<style>
h3 {
  margin-bottom: 0;
}
</style>

Post.vue

<template>
  <div class="post">
    <h2>{{ post.title }}</h2>

    <p>{{ post.body }}</p>

    <h3>Comments:</h3>
    <ul>
      <li v-for="comment in post.comments" :key="comment.id">
        <div>{{ comment.name }}</div>
        <div>{{ comment.email }}</div>
        <div>{{ comment.body }}</div>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      post: {}
    }
  },

  created() {
    const postId = this.$route.params.id
    const post = this.$root.posts.find(post => post.id === Number(postId))
    this.post = post
  }
}
</script>

<style>
h2 {
  margin-bottom: 0;
}

h3 {
  margin-top: 2rem;
  margin-bottom: 0;
}
</style>

结语

本文通过一个简单的论坛应用程序,介绍了VUE3的基本用法和实例。希望本文对初学者的学习有所帮助。