vue写一个关注功能,为何第一次关注时切换按钮不起效?(但请求发出去了,此时点击其它的“取消关注”才会切换。)

写了两个按钮,用muse-ui.

结果第一次关注时无法切换(但请求发出去了,此时点击其它的“取消关注”才会切换。)
刷新后,已是“取消关注”的功能正常。

//这是按钮:
<mu-flat-button label="+ 关注" class="demo-flat-button" v-if="!item.user_followed"  @click="myFollow(item)" />
<mu-flat-button label="已关注" class="demo-flat-button" id="followed"  v-else="item.user_followed" @click="unFollow(item)"/>

//对应方法及请求
methods:{

//关注
 myFollow (item) {
        var _this = this;
        axios.post('关注的请求‘).then(function (res) {
            item.user_followed = true
        })
      },
      
//取消关注      
unFollow (item) {
        var _this = this;
        axios.post('取消关注的请求').then(function (res) {
            item.user_followed = false
        })
      }
}
阅读 4.6k
4 个回答

我对vue不是太熟悉,并且不知道你vue.List代表是什么
但是,

axios.post('关注的请求‘).then(function (res) {
  ***_this.List.splice(_this.List.indexOf(item), 1, item);***
  //有回应时改变按钮

_this.List.splice(_this.List.indexOf(item), 1, item)这段代码有没有问题呢?
如果第一次关注,_this.List.indexOf(item)肯定是返回-1的

//这是按钮:
<mu-flat-button label="+ 关注" class="demo-flat-button" v-if="!item.user_followed"  @click="myFollow(item)" />
<mu-flat-button label="已关注" class="demo-flat-button" id="followed"  v-else="item.user_followed" @click="unFollow(item)"/>

这里,你改成这样试试,v-if改为v-show

    <mu-flat-button label="+ 关注" class="demo-flat-button" v-show="!item.user_followed"  @click="myFollow(item)" />
    <mu-flat-button label="已关注" class="demo-flat-button" id="followed"  v-show="item.user_followed" @click="unFollow(item)"/>

问题在这段代码:

axios.post('关注的请求‘).then(function (res) {
      _this.List.splice(_this.List.indexOf(item), 1, item);
      //有回应时改变按钮
      if(res.data.cd==="200" ){     // 如果确定这个条件会满足
        item.user_followed = true // <-- 前面加个this, this.item.user_followed = true
      }
    })

这里的item 没必要通过函数传递进来,因为直接this.item就好了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题