社区板块添加点赞功能

This commit is contained in:
橙子
2022-11-29 23:03:10 +08:00
parent 9a34e63d5f
commit a2ca897fca
11 changed files with 133 additions and 84 deletions

View File

@@ -23,11 +23,11 @@ namespace Yi.Framework.ApiMicroservice.Controllers
public class AgreeController : ControllerBase public class AgreeController : ControllerBase
{ {
[Autowired] [Autowired]
public IAgreeService _iAgreeService { get; set; } public IAgreeService? _iAgreeService { get; set; }
[Autowired] [Autowired]
public IArticleService _iArticleService { get; set; } public IArticleService? _iArticleService { get; set; }
[Autowired] [Autowired]
public ILogger<AgreeEntity> _logger { get; set; } public ILogger<AgreeEntity>? _logger { get; set; }
/// <summary> /// <summary>
/// 点赞操作 /// 点赞操作
@@ -37,30 +37,16 @@ namespace Yi.Framework.ApiMicroservice.Controllers
[HttpGet] [HttpGet]
public async Task<Result> Operate(long articleId) public async Task<Result> Operate(long articleId)
{ {
//long userId = HttpContext.GetUserIdInfo(); long userId = HttpContext.GetUserIdInfo();
long userId = 1L; if (await _iAgreeService!.OperateAsync(articleId, userId))
var article = await _iArticleService._repository.GetByIdAsync(articleId);
if (await _iAgreeService._repository.IsAnyAsync(u => u.UserId == userId && u.ArticleId == articleId))
{ {
//已点赞,取消点赞 return Result.Success("点赞成功");
await _iAgreeService._repository.UseTranAsync(async () =>
{
await _iAgreeService._repository.DeleteAsync(u => u.UserId == userId && u.ArticleId == articleId);
await _iArticleService._repository.UpdateIgnoreNullAsync(new ArticleEntity { Id = articleId, AgreeNum = article.AgreeNum - 1 });
});
} }
else else
{ {
//未点赞,添加点赞记录 return Result.Success("已点赞,取消点赞").StatusFalse();
await _iAgreeService._repository.UseTranAsync(async () =>
{
await _iAgreeService._repository.InsertAsync(new AgreeEntity { UserId = userId, ArticleId = articleId });
await _iArticleService._repository.UpdateIgnoreNullAsync(new ArticleEntity { Id = articleId, AgreeNum = article.AgreeNum + 1 });
});
} }
return Result.Success("这里业务全部拆开放service层去");
} }
} }
} }

View File

@@ -33,6 +33,7 @@ namespace Yi.Framework.DTOModel.Vo
public string Remark { get; set; } public string Remark { get; set; }
public List<string> Images { get; set; } public List<string> Images { get; set; }
public int? AgreeNum { get; set; }
public UserVo User { get; set; } public UserVo User { get; set; }
} }
} }

View File

@@ -0,0 +1,11 @@
using System.Threading.Tasks;
using Yi.Framework.Model.Models;
using Yi.Framework.Repository;
namespace Yi.Framework.Interface
{
public partial interface IAgreeService : IBaseService<AgreeEntity>
{
Task<bool> OperateAsync(long articleId, long userId);
}
}

View File

@@ -1,9 +1,10 @@
using Yi.Framework.Model.Models; using System.Threading.Tasks;
using Yi.Framework.Model.Models;
using Yi.Framework.Repository; using Yi.Framework.Repository;
namespace Yi.Framework.Interface namespace Yi.Framework.Interface
{ {
public partial interface IAgreeService:IBaseService<AgreeEntity> public partial interface IAgreeService : IBaseService<AgreeEntity>
{ {
} }
} }

View File

@@ -14,6 +14,7 @@ namespace Yi.Framework.Model.Models
public ArticleEntity() public ArticleEntity()
{ {
this.CreateTime = DateTime.Now; this.CreateTime = DateTime.Now;
this.AgreeNum = 0;
} }
[JsonConverter(typeof(ValueToStringConverter))] [JsonConverter(typeof(ValueToStringConverter))]
[SugarColumn(ColumnName="Id" ,IsPrimaryKey = true )] [SugarColumn(ColumnName="Id" ,IsPrimaryKey = true )]
@@ -22,12 +23,12 @@ namespace Yi.Framework.Model.Models
/// 文章标题 /// 文章标题
///</summary> ///</summary>
[SugarColumn(ColumnName="Title" )] [SugarColumn(ColumnName="Title" )]
public string Title { get; set; } public string? Title { get; set; }
/// <summary> /// <summary>
/// 文章内容 /// 文章内容
///</summary> ///</summary>
[SugarColumn(ColumnName="Content" )] [SugarColumn(ColumnName="Content" )]
public string Content { get; set; } public string? Content { get; set; }
/// <summary> /// <summary>
/// 用户id /// 用户id
///</summary> ///</summary>
@@ -72,16 +73,16 @@ namespace Yi.Framework.Model.Models
/// 描述 /// 描述
///</summary> ///</summary>
[SugarColumn(ColumnName="Remark" )] [SugarColumn(ColumnName="Remark" )]
public string Remark { get; set; } public string? Remark { get; set; }
/// <summary> /// <summary>
/// 图片列表 /// 图片列表
///</summary> ///</summary>
[SugarColumn(ColumnName="Images" )] [SugarColumn(ColumnName = "Images", IsJson = true)]
public string Images { get; set; } public List<string>? Images { get; set; }
/// <summary> /// <summary>
/// 点赞数量 /// 点赞数量
///</summary> ///</summary>
[SugarColumn(ColumnName="AgreeNum" )] [SugarColumn(ColumnName="AgreeNum" )]
public int? AgreeNum { get; set; } public int AgreeNum { get; set; }
} }
} }

View File

@@ -0,0 +1,42 @@
using SqlSugar;
using System.Threading.Tasks;
using Yi.Framework.Interface;
using Yi.Framework.Model.Models;
using Yi.Framework.Repository;
namespace Yi.Framework.Service
{
public partial class AgreeService : BaseService<AgreeEntity>, IAgreeService
{
/// <summary>
/// 点赞操作
/// </summary>
/// <returns></returns>
public async Task<bool> OperateAsync(long articleId, long userId)
{
var _articleRepositoty = _repository.ChangeRepository<Repository<ArticleEntity>>();
var article = await _articleRepositoty.GetByIdAsync(articleId);
if (await _repository.IsAnyAsync(u => u.UserId == userId && u.ArticleId == articleId))
{
//已点赞,取消点赞
await _repository.UseTranAsync(async () =>
{
await _repository.DeleteAsync(u => u.UserId == userId && u.ArticleId == articleId);
await _articleRepositoty.UpdateIgnoreNullAsync(new ArticleEntity { Id = articleId, AgreeNum = article.AgreeNum - 1 });
});
return false;
}
else
{
//未点赞,添加点赞记录
await _repository.UseTranAsync(async () =>
{
await _repository.InsertReturnSnowflakeIdAsync(new AgreeEntity { UserId = userId, ArticleId = articleId });
await _articleRepositoty.UpdateIgnoreNullAsync(new ArticleEntity { Id = articleId, AgreeNum = article.AgreeNum + 1 });
});
return true;
}
}
}
}

View File

@@ -16,7 +16,6 @@ declare module '@vue/runtime-core' {
RouterView: typeof import('vue-router')['RouterView'] RouterView: typeof import('vue-router')['RouterView']
VanActionSheet: typeof import('vant/es')['ActionSheet'] VanActionSheet: typeof import('vant/es')['ActionSheet']
VanButton: typeof import('vant/es')['Button'] VanButton: typeof import('vant/es')['Button']
VanCell: typeof import('vant/es')['Cell']
VanCellGroup: typeof import('vant/es')['CellGroup'] VanCellGroup: typeof import('vant/es')['CellGroup']
VanCol: typeof import('vant/es')['Col'] VanCol: typeof import('vant/es')['Col']
VanDivider: typeof import('vant/es')['Divider'] VanDivider: typeof import('vant/es')['Divider']
@@ -28,12 +27,9 @@ declare module '@vue/runtime-core' {
VanList: typeof import('vant/es')['List'] VanList: typeof import('vant/es')['List']
VanLoading: typeof import('vant/es')['Loading'] VanLoading: typeof import('vant/es')['Loading']
VanNavBar: typeof import('vant/es')['NavBar'] VanNavBar: typeof import('vant/es')['NavBar']
VanPopup: typeof import('vant/es')['Popup']
VanPullRefresh: typeof import('vant/es')['PullRefresh'] VanPullRefresh: typeof import('vant/es')['PullRefresh']
VanRow: typeof import('vant/es')['Row'] VanRow: typeof import('vant/es')['Row']
VanSticky: typeof import('vant/es')['Sticky'] VanSticky: typeof import('vant/es')['Sticky']
VanSwipe: typeof import('vant/es')['Swipe']
VanSwipeItem: typeof import('vant/es')['SwipeItem']
VanTab: typeof import('vant/es')['Tab'] VanTab: typeof import('vant/es')['Tab']
VanTabbar: typeof import('vant/es')['Tabbar'] VanTabbar: typeof import('vant/es')['Tabbar']
VanTabbarItem: typeof import('vant/es')['TabbarItem'] VanTabbarItem: typeof import('vant/es')['TabbarItem']

View File

@@ -0,0 +1,11 @@
import myaxios from '@/utils/myaxios'
export default {
operate(data:any) {
return myaxios({
url: `/agree/operate`,
method: 'get',
params: {articleId:data}
})
},
}

View File

@@ -55,6 +55,12 @@ myaxios.interceptors.response.use(async function(response) {
return resp; return resp;
}, async function(error) { }, async function(error) {
//未授权、失败 //未授权、失败
if(error.response==undefined)
{
Notify({ type: 'danger', message: `服务器异常:${error.message}` });
return Promise.reject(error);;
}
const resp = error.response.data const resp = error.response.data
if (resp.code == undefined && resp.message == undefined) { if (resp.code == undefined && resp.message == undefined) {
Notify({ type: 'danger', message: '未知错误' }); Notify({ type: 'danger', message: '未知错误' });

View File

@@ -1,24 +1,14 @@
<template> <template>
<van-pull-refresh v-model="refreshing" @refresh="onRefresh"> <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
<van-list <van-list class="list" v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
class="list"
v-model:loading="loading"
:finished="finished"
finished-text="没有更多了"
@load="onLoad"
>
<van-row v-for="(item, index) in articleList" :key="index" class="row"> <van-row v-for="(item, index) in articleList" :key="index" class="row">
<van-col span="4" class="leftCol"> <van-col span="4" class="leftCol">
<AppUserIcon <AppUserIcon width="3rem" height="3rem" :src="item.user == null ? null : item.user.icon" />
width="3rem"
height="3rem"
:src="item.user == null ? null : item.user.icon"
/>
</van-col> </van-col>
<van-col span="14" class="centerTitle"> <van-col span="14" class="centerTitle">
<span class="justtitle">{{ <span class="justtitle">{{
item.user == null ? "-" : item.user.nick ?? item.user.username item.user == null ? "-" : item.user.nick ?? item.user.username
}}</span> }}</span>
<br /> <br />
<app-createTime :time="item.createTime" /> <app-createTime :time="item.createTime" />
@@ -30,20 +20,9 @@
<van-col class="rowBody" span="24">{{ item.content }}</van-col> <van-col class="rowBody" span="24">{{ item.content }}</van-col>
<van-col <van-col span="8" v-for="(image, imageIndex) in item.images" :key="imageIndex" class="imageCol"
span="8" @click="openImage(item.images, imageIndex)">
v-for="(image, imageIndex) in item.images" <van-image lazy-load fit="cover" width="100%" height="7rem" :src="url + image + '/true'" radius="5" />
:key="imageIndex"
class="imageCol"
@click="openImage(item.images, imageIndex)"
><van-image
lazy-load
fit="cover"
width="100%"
height="7rem"
:src="url + image + '/true'"
radius="5"
/>
<template v-slot:loading> <template v-slot:loading>
<van-loading type="spinner" size="20" /> <van-loading type="spinner" size="20" />
</template> </template>
@@ -52,40 +31,30 @@
<van-col span="24" class="bottomRow"> <van-col span="24" class="bottomRow">
<van-grid direction="horizontal" :column-num="3"> <van-grid direction="horizontal" :column-num="3">
<van-grid-item icon="share-o" text="分享" /> <van-grid-item icon="share-o" text="分享" />
<van-grid-item icon="comment-o" text="评论" @click="commentShow=true" /> <van-grid-item icon="comment-o" text="评论" @click="commentShow = true" />
<van-grid-item icon="good-job-o" text="点赞" /> <van-grid-item icon="good-job-o" :text="`点赞:${item.agreeNum}`" @click="aggreeHand(item.id)" />
</van-grid> </van-grid>
</van-col> </van-col>
</van-row> </van-row>
</van-list> </van-list>
</van-pull-refresh> </van-pull-refresh>
<!-- 功能页面 --> <!-- 功能页面 -->
<van-action-sheet <van-action-sheet v-model:show="show" :actions="actions" cancel-text="取消" close-on-click-action />
v-model:show="show"
:actions="actions"
cancel-text="取消"
close-on-click-action
/>
<!-- 图片预览 --> <!-- 图片预览 -->
<van-image-preview <van-image-preview v-model:show="imageShow" :images="imagesPreview" :startPosition="startIndex" @change="onChange"
v-model:show="imageShow" :closeable="true">
:images="imagesPreview"
:startPosition="startIndex"
@change="onChange"
:closeable="true"
>
<template v-slot:index>{{ index + 1 }}</template> <template v-slot:index>{{ index + 1 }}</template>
</van-image-preview> </van-image-preview>
<!-- 评论面板 --> <!-- 评论面板 -->
<van-action-sheet v-model:show="commentShow" title="共10条评论"> <van-action-sheet v-model:show="commentShow" title="共10条评论">
<van-row v-for="i of 10" :key="i" class="commentContent"> <van-row v-for="i of 10" :key="i" class="commentContent">
<van-col span="4">头像</van-col> <van-col span="4">头像</van-col>
<van-col span="16">内容</van-col> <van-col span="16">内容</van-col>
<van-col span="4">点赞</van-col> <van-col span="4">点赞</van-col>
</van-row> </van-row>
</van-action-sheet> </van-action-sheet>
</template> </template>
@@ -95,6 +64,7 @@ import { ImagePreview, Toast } from "vant";
import AppCreateTime from "@/components/AppCreateTime.vue"; import AppCreateTime from "@/components/AppCreateTime.vue";
import AppUserIcon from "@/components/AppUserIcon.vue"; import AppUserIcon from "@/components/AppUserIcon.vue";
import articleApi from "@/api/articleApi"; import articleApi from "@/api/articleApi";
import agreeApi from "@/api/agreeApi";
import { ArticleEntity } from "@/type/interface/ArticleEntity"; import { ArticleEntity } from "@/type/interface/ArticleEntity";
const VanImagePreview = ImagePreview.Component; const VanImagePreview = ImagePreview.Component;
const url = `${import.meta.env.VITE_APP_BASE_API}/file/`; const url = `${import.meta.env.VITE_APP_BASE_API}/file/`;
@@ -112,7 +82,7 @@ const { queryParams } = toRefs(data);
const articleList = ref<any[]>([]); const articleList = ref<any[]>([]);
const totol = ref<Number>(0); const totol = ref<Number>(0);
const imageShow = ref(false); const imageShow = ref(false);
const commentShow=ref(false) const commentShow = ref(false)
const index = ref(0); const index = ref(0);
let imagesPreview = ref<string[]>([]); let imagesPreview = ref<string[]>([]);
@@ -176,11 +146,26 @@ const getList = () => {
totol.value = response.data.totol; totol.value = response.data.totol;
}); });
}; };
const aggreeHand = (articleId: any) => {
agreeApi.operate(articleId).then((response: any) => {
//更改显示的值
if (response.status) {
articleList.value.filter(p => p.id == articleId)[0].agreeNum += 1
} else {
articleList.value.filter(p => p.id == articleId)[0].agreeNum -= 1
}
Toast({
message: response.message,
position: 'bottom',
})
})
}
</script> </script>
<style scoped> <style scoped>
.list { .list {
background-color: #f4f4f4; background-color: #f4f4f4;
} }
.row { .row {
background-color: white; background-color: white;
padding-top: 1rem; padding-top: 1rem;
@@ -188,6 +173,7 @@ const getList = () => {
padding-right: 1rem; padding-right: 1rem;
margin-bottom: 0.6rem; margin-bottom: 0.6rem;
} }
.rowBody { .rowBody {
text-align: left; text-align: left;
background-color: white; background-color: white;
@@ -195,22 +181,27 @@ const getList = () => {
margin-top: 1rem; margin-top: 1rem;
margin-bottom: 1rem; margin-bottom: 1rem;
} }
.title { .title {
padding-top: 1rem; padding-top: 1rem;
min-height: 3rem; min-height: 3rem;
text-align: left; text-align: left;
} }
.leftCol { .leftCol {
align-content: left; align-content: left;
text-align: left; text-align: left;
} }
.centerTitle { .centerTitle {
text-align: left; text-align: left;
} }
.imageCol { .imageCol {
padding: 0.1rem 0.1rem 0.1rem 0.1rem; padding: 0.1rem 0.1rem 0.1rem 0.1rem;
} }
.subtitle { .subtitle {
color: #cbcbcb; color: #cbcbcb;
} }
@@ -218,14 +209,17 @@ const getList = () => {
.justtitle { .justtitle {
font-size: large; font-size: large;
} }
.bottomRow { .bottomRow {
color: #999999; color: #999999;
} }
.down { .down {
text-align: right; text-align: right;
padding-right: 0.5rem; padding-right: 0.5rem;
} }
.commentContent { .commentContent {
margin-bottom: 4rem; margin-bottom: 4rem;
} }
</style> </style>