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

请看这个最小的例子:


<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>


慕田峪4524236
浏览 118回答 1
1回答

萧十郎

不可能将这样的设置器“复制”到局部变量中。您可以使用自己的 setter 抽象方法或另一个对象背后的属性:click() {&nbsp; const self = this&nbsp; const wrapper = {&nbsp; &nbsp; get count() { return self.count },&nbsp; &nbsp; set count(x) { self.count = x }&nbsp; }&nbsp; wrapper.count++}我觉得这是一个 XY 问题;你为什么要这样做?你想达到什么目的?您最好将局部变量重新分配给 data 属性以触发更新:click() {&nbsp; let count = this.count&nbsp; // Modify local var&nbsp; count++&nbsp; // Assign back to trigger the update&nbsp; this.count = count}更新您可以通过其字符串名称动态访问该属性:hitAPI(type: "A" | "B") {&nbsp; const prop = type === "A" ? "isALoading" : "isBLoading"&nbsp; this[prop] = true&nbsp; fetch(someAPI).finally(() => {&nbsp; &nbsp; this[prop] = false&nbsp; })}或者使用async/ await:async hitAPI(type: "A" | "B") {&nbsp; const prop = type === "A" ? "isALoading" : "isBLoading"&nbsp; this[prop] = true&nbsp; try {&nbsp; &nbsp; await fetch(someAPI)&nbsp; } finally {&nbsp; &nbsp; this[prop] = false&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript