博主
258
258
258
258
专辑

第二十四节 Vue实现关注按钮状态的改变

亮子 2024-07-01 01:48:58 3259 0 0 0

1、前端代码

<template>
    <div>
        <div><el-button type="success" @click="onChangeUser">换一批</el-button></div>
        <el-row :gutter="10">
            <el-col :span="6" v-for="item in strangers" :key="item.userId">
                <el-card style="max-width: 480px" class="ff">
                    <template #header>
                    <div class="card-header">
                        <span>{{item.nickName}}</span>
                        <el-tag type="primary" v-if="item.gender=='man'">男</el-tag>
                        <el-tag type="danger" v-if="item.gender=='woman'">女</el-tag>
                    </div>
                    </template>
                    <el-image :src="item.avatar" fit="contain" class="stranger"></el-image>
                    <template #footer>
                        <el-button type="primary" @click="onFollowUser($event, item.userId)">关注</el-button>
                    </template>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

2、TS代码

// 关注用户
const onFollowUser = (obj:any, followId:any) => {

    let flag = 1;
    if(obj.target.innerText == '关注') {
        flag = 1;
        obj.target.innerText = '取消关注';
    }
    else {
        flag = 0;
        obj.target.innerText = '关注';
    }
    // 发送关注/取消关注请求
    doFollow(user.value.id, followId, flag).then(res => {
        console.log('doFollow', res);
        if(res.data.code == 200) {
            ElMessage.success('操作成功')
        }
        else {
            let msg = res.data.msg;
            ElMessage.error(msg);
        }
        
    })
}