返回

基于 Vue 3 + Vant 3 的类掘金 App 项目 - 作者列表推荐的实现

前端

在上一篇文章中,我们共同探讨了如何使用 Vue 3 和 Vant 3 来实现类掘金 App 项目的关注页面推荐作者头像展示,以及其他几个列表页中子标签组件 JTags 的封装和使用,从而实现了子标签的动态加载。今天,我们将继续深入挖掘,探索如何实现作者列表推荐功能中的更多细节,包括头像展示、标签展示以及动态加载子标签组件等。

一、定义 AuthorList 和 AuthorCard 组件

首先,我们需要定义一个名为 AuthorList 的 Vue 组件,它将负责渲染作者列表。该组件包含一个名为 authors 的数据属性,用于存储要显示的作者数据。同时,我们还需要一个名为 AuthorCard 的 Vue 组件,它将负责渲染单个作者的卡片,包括头像、姓名、标签等信息。

<!-- AuthorList.vue -->
<template>
  <div class="author-list">
    <author-card
      v-for="author in authors"
      :key="author.id"
      :author="author"
    />
  </div>
</template>

<script>
import AuthorCard from './AuthorCard.vue';

export default {
  components: { AuthorCard },
  props: {
    authors: {
      type: Array,
      required: true,
    },
  },
};
</script>
<!-- AuthorCard.vue -->
<template>
  <div class="author-card">
    <img class="avatar" :src="author.avatar" alt="作者头像" />
    <div class="info">
      <h3 class="name">{{ author.name }}</h3>
      <div class="tags">
        <span class="tag" v-for="tag in author.tags" :key="tag">{{ tag }}</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    author: {
      type: Object,
      required: true,
    },
  },
};
</script>

二、定义 Author 数据模型

接下来,我们需要定义一个名为 Author 的数据模型,它将用于存储单个作者的信息,包括 ID、姓名、头像 URL、标签等。

// data.js
export default class Author {
  constructor(id, name, avatar, tags) {
    this.id = id;
    this.name = name;
    this.avatar = avatar;
    this.tags = tags;
  }
}

三、构建作者列表推荐功能

现在,我们就可以使用这些组件和数据模型来构建作者列表推荐功能了。首先,我们需要在父组件中获取作者数据,然后将这些数据传递给 AuthorList 组件。AuthorList 组件将使用这些数据来渲染作者卡片列表。当用户点击某个作者卡片时,我们可以使用路由导航到该作者的个人主页。

<!-- App.vue -->
<template>
  <author-list :authors="authors" />
</template>

<script>
import AuthorList from './components/AuthorList.vue';
import { authors } from './data';

export default {
  components: { AuthorList },
  data() {
    return {
      authors: authors,
    };
  },
};
</script>

四、定义路由规则

最后,我们需要在路由文件中定义路由规则,以便当用户点击作者卡片时,可以导航到该作者的个人主页。

// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import AuthorProfile from '../views/AuthorProfile.vue';

const routes = [
  {
    path: '/authors/:id',
    component: AuthorProfile,
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

export default router;

通过以上步骤,我们已经成功实现了基于 Vue 3 和 Vant 3 的类掘金 App 项目中的作者列表推荐功能,包括头像展示、标签展示以及动态加载子标签组件等。希望本文对您有所帮助,也欢迎您在评论区留下您的想法和建议。

相关资源链接