报错Unexpected side effect in "listShow" computed property

慕课网教程listShow计算下面购物车弹窗遇到问题

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即可。

你可能感兴趣的:(学习笔记)