Uniapp取消关注

275 阅读2分钟

一、简介

在Uniapp中设置取消关注按钮,分两种情况:(1)未关注,点击按钮后内容变为“已关注”,边框颜色改为灰色;(2)已关注,点击按钮后弹出一个弹窗,样式如下。点击确定则取消关注,按钮内容变为“关注”,边框颜色改为橙色。

image.png

二、步骤

1. 点击按钮改变内容和边框

(1)内容改变

html内容

<!-- 给按钮绑定一个点击事件,修改likes的值来决定内容的显示 -->
<view class="bottom" v-for="item in listArr" index="item.id">
	<view  class="attention" @click="getUserInfo(item)">{{item.likes=='0'?'已关注':'关注'}}</view>
</view>

js内容

getUserInfo(e){
    let index = e.id
    let that = this
    let likes = e.likes
    if (likes==1){
    that.listArr[index].likes = 0;
    }else{
    that.listArr[index].likes = 1;
    }
}

(2)边框改变

html内容

<!-- 声明布尔值isColor来决定attentionBg样式是否显示 -->
<view class="bottom" v-for="item in listArr" index="item.id">
	<view  class="attention" :class='{attentionBg:item.isColor}' @click="getUserInfo(item)">{{item.likes=='0'?'已关注':'关注'}}</view>
</view>

css内容

/* 如果isColor为true则该样式显示,否则按钮颜色默认 */
  .attentionBg {
        border: 1rpx solid rgba(255, 141, 26, 1);
	color:  rgba(255, 141, 26, 1);
  }

js内容

getUserInfo(e){
    let index = e.id
    let that = this
    let likes = e.likes
    if (likes==1){
    that.listArr[index].likes = 0;
    that.listArr[index].isColor =false;
    }else{
    that.listArr[index].likes = 1;
    that.listArr[index].isColor =true;
    }
}

2. 创建弹出层

html内容

<!-- 和边框样式改变类似,利用boolean值isTrue来决定outlay样式是否显示 -->
<view class="overlay" :class='{outlay:item.isTrue}'>
    <view class="popup">
        <view class="popup_content">确认不再关注?</view>
        <view class="popup_btn">
            <button class="cancelBtn" @click="Confirm(item)">确认</button>
            <button class="confirmBtn" @click="Cancel(item)">取消</button>
        </view>
    </view>
</view>

css内容

  /* 遮罩层 */
  .overlay {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.5);
    display: none;
  }
  /*如果Boolean值outlay为True则改样式显示*/
  .outlay {
    display: block;
  }
  /* 弹出框的内容 */
  .popup {
  ...
  }

3. 写弹出层逻辑

js内容

getUserInfo(e){
    let index = e.id
    let that = this
    let likes = e.likes
    // 若未关注,则直接修改样式即可 
    if (likes==1){
    that.listArr[index].likes = 0;
    that.listArr[index].isColor =false;
    }else{
    // 取消关注需要确认,此时置isTrue为true,弹出层打开 
    that.listArr[index].isTrue = true;
    }
},
// 不取消关注,不做任何事情,关闭弹出层
Cancel(e){
    let index = e.id;
    let that = this;
    that.listArr[index].isTrue = false;
}
// 取消关注,将颜色和样式修改,并关闭弹出层
Confirm(e){
    let index = e.id;
    let that = this;
    that.listArr[index].isTrue = false;
    that.listArr[index].likes = 1;
    that.listArr[index].isColor =true;
},

三、总结

这个页面主要是一个弹出层的问题,它的显隐利用动态绑定class样式来决定,当class绑定的布尔值为ture时,对应样式显示,覆盖原有样式,弹出层显示。