为了账号安全,请及时绑定邮箱和手机立即绑定

我可以将 Vue.js 数据属性连同它的设置器一起分配给局部变量吗?

我可以将 Vue.js 数据属性连同它的设置器一起分配给局部变量吗?

慕田峪4524236 2022-06-16 17:30:31
请看这个最小的例子:<template>  <div>    {{ count }}    <button @click="click">Click</button>  </div></template><script>export default {  data() {    return {      count: 0    }  },  methods: {    click() {      this.count++    }  }};</script>我有一个计数数据属性和一个可以增加计数的按钮。现在,我想这样做有点不同(出于某种原因)click() {  let count = this.count  count += 1}我想先将我的数据属性分配给我的局部变量,然后增加局部变量计数,并希望触发 Vue 的反应性。我知道 Vue 使用Object.definePropertysetter 到 data 属性,我怎样才能克隆那些 setter?是否有可能做到这一点?更新我想要做的是尝试简化下面的代码<script>export default {  data() {    return {      isALoading: false,      isBLoading: false    };  },  methods: {    hitAPI(type: "A" | "B") {      if (type === "A") {        this.isALoading = true;        fetch(someAPI)          .then(() => {            this.isALoading = false;          })          .catch(() => {            this.isALoading = false;          });      } else {        this.isBLoading = true;        fetch(someAPI)          .then(() => {            this.isBLoading = false;          })          .catch(() => {            this.isBLoading = false;          });      }    }  }};</script>
查看完整描述

1 回答

?
萧十郎

TA贡献1815条经验 获得超13个赞

不可能将这样的设置器“复制”到局部变量中。


您可以使用自己的 setter 抽象方法或另一个对象背后的属性:


click() {

  const self = this

  const wrapper = {

    get count() { return self.count },

    set count(x) { self.count = x }

  }


  wrapper.count++

}

我觉得这是一个 XY 问题;你为什么要这样做?你想达到什么目的?


您最好将局部变量重新分配给 data 属性以触发更新:


click() {

  let count = this.count


  // Modify local var

  count++


  // Assign back to trigger the update

  this.count = count

}

更新


您可以通过其字符串名称动态访问该属性:


hitAPI(type: "A" | "B") {

  const prop = type === "A" ? "isALoading" : "isBLoading"

  this[prop] = true


  fetch(someAPI).finally(() => {

    this[prop] = false

  })

}

或者使用async/ await:


async hitAPI(type: "A" | "B") {

  const prop = type === "A" ? "isALoading" : "isBLoading"

  this[prop] = true


  try {

    await fetch(someAPI)

  } finally {

    this[prop] = false

  }

}


查看完整回答
反对 回复 2022-06-16
  • 1 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号