报错Unexpected side effect in "listShow" computed property

慕课网教程listShow计算下面购物车弹窗遇到问题
<div class="shopcart-list" v-show="listShow">
</div>

listShow() {
      if (!this.totalCount) {
        this.fold = true
        return false
      }
      let show = !this.fold
      if (show) {
        this.$nextTick(() => {
          if (!this.scroll) {
            this.scroll = new BScroll(this.$refs.listContent, {
              click: true
            })
          } else {
            this.scroll.refresh()
          }
        })
      }
      return show
    }

报错

  https://google.com/#q=vue%2Fno-side-effects-in-computed-properties  Unexpected side effect in "listShow" computed property
  src\components\shopcart\shopcart.vue:129:16
          return this.fold = true

参照其他人的教程修改

listShow: {
  get: function () {
    return this.fold
  },
  set: function () {
    if (!this.totalCount) {
      this.fold = true
      return false
    }
    let show = !this.fold
    return show
  }
}

虽然没有报错了,还是存在当totalCount为0时,购物车不能收起来。vue教程里说

计算属性的 setter

计算属性默认只有 getter ,不过在需要时你也可以提供一个 setter :

// ...
computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}
// ...

现在再运行 vm.fullName = 'John Doe' 时,setter 会被调用,vm.firstName 和 vm.lastName 也会相应地被更新。

大意为只有set里面函数传入的参数发生变化时,set才起作用。

后来,将v-show用watch来观测,还是存在当totalCount为0时,购物车不能收起来的问题。暂时还没得到解决

watch: {
    
watch: {
fold : function() {
if (! this. totalCount) {
this. fold = false
return false
}
console. log( this. totalCount)
let show = this. fold
if ( show) {
this. $nextTick(() => {
if (! this. scroll) {
this. scroll = new BScroll( this. $refs. listContent, {
click: true
})
} else {
this. scroll. refresh()
}
})
}
console. log( this. fold)
return show
}
},

watch观测fold的时候,totalCount的值没有观察到,于是再观察totalCount的值。

watch: {
    totalCount: function() {
      if (!this.totalCount) {
        this.fold = false
        return false
      }
    },
    fold: function(totalCount) {
      let show = this.fold
      if (show) {
        this.$nextTick(() => {
          if (!this.scroll) {
            this.scroll = new BScroll(this.$refs.listContent, {
              click: true
            })
          } else {
            this.scroll.refresh()
          }
        })
      }
      return show
    }
  },
当totalCount为0的时候,fold为false即可。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值