Initial commit
This commit is contained in:
87
miniprogram/components/post-card/post-card.ts
Normal file
87
miniprogram/components/post-card/post-card.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { Post } from '../../types/index'
|
||||
import { formatTime, formatCount, getAvatarGradient } from '../../utils/format'
|
||||
import { api } from '../../utils/api'
|
||||
|
||||
Component({
|
||||
properties: {
|
||||
post: {
|
||||
type: Object,
|
||||
value: null,
|
||||
},
|
||||
},
|
||||
|
||||
data: {
|
||||
avatarGradient: '',
|
||||
timeText: '',
|
||||
likeCount: 0,
|
||||
},
|
||||
|
||||
observers: {
|
||||
post(val: Post) {
|
||||
if (!val) return
|
||||
this.setData({
|
||||
avatarGradient: getAvatarGradient(val.authorId || ''),
|
||||
timeText: formatTime(val.createdAt),
|
||||
likeCount: val.likeCount,
|
||||
})
|
||||
},
|
||||
},
|
||||
|
||||
methods: {
|
||||
onCardTap() {
|
||||
const post = this.data.post as Post
|
||||
if (!post) return
|
||||
wx.navigateTo({ url: `/pages/post-detail/post-detail?id=${post._id}` })
|
||||
},
|
||||
|
||||
onAuthorTap(e: WechatMiniprogram.CustomEvent) {
|
||||
e.stopPropagation()
|
||||
const post = this.data.post as Post
|
||||
if (!post?.authorId) return
|
||||
wx.navigateTo({ url: `/pages/pet-detail/pet-detail?userId=${post.authorId}` })
|
||||
},
|
||||
|
||||
onImageTap(e: WechatMiniprogram.CustomEvent) {
|
||||
const post = this.data.post as Post
|
||||
if (!post?.images?.length) return
|
||||
wx.previewImage({
|
||||
current: post.images[e.currentTarget.dataset.idx as number],
|
||||
urls: post.images,
|
||||
})
|
||||
},
|
||||
|
||||
async onLike(e: WechatMiniprogram.CustomEvent) {
|
||||
e.stopPropagation()
|
||||
const post = this.data.post as Post
|
||||
if (!post) return
|
||||
const wasLiked = post.isLiked
|
||||
const prevCount = this.data.likeCount
|
||||
|
||||
this.setData({
|
||||
'post.isLiked': !wasLiked,
|
||||
likeCount: wasLiked ? prevCount - 1 : prevCount + 1,
|
||||
})
|
||||
|
||||
try {
|
||||
const res = await api.likePost(post._id)
|
||||
this.setData({ likeCount: res.count, 'post.isLiked': res.liked })
|
||||
this.triggerEvent('likeChange', { postId: post._id, liked: res.liked, count: res.count })
|
||||
} catch {
|
||||
this.setData({ 'post.isLiked': wasLiked, likeCount: prevCount })
|
||||
wx.showToast({ title: '操作失败', icon: 'none' })
|
||||
}
|
||||
},
|
||||
|
||||
onComment(e: WechatMiniprogram.CustomEvent) {
|
||||
e.stopPropagation()
|
||||
const post = this.data.post as Post
|
||||
if (!post) return
|
||||
wx.navigateTo({ url: `/pages/post-detail/post-detail?id=${post._id}&focus=comment` })
|
||||
},
|
||||
|
||||
onShare(e: WechatMiniprogram.CustomEvent) {
|
||||
e.stopPropagation()
|
||||
wx.showShareMenu({ withShareTicket: true, menus: ['shareAppMessage', 'shareTimeline'] })
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user