Skip to content
    在 Opshell 的 Blog 中:
  • 目前已分享 62 篇文章
  • 還有 67 個坑正在填補中
  • 已有: Loading 次觀看
  • 已有: Loading 個人來過
✍️ Opshell
📆 Last Updated:8/23/2024Created:2024/08/23
👀 已被閱讀: Loading
🏷️ javascriptvue

this

這是一個 QR CODE 讀取的例子

javascript
const res = await userApi(form);
const reader = new FileReader();

reader.readAsDataURL(res.data);
reader.onload = function () {
  qrCodeSrc.value = this.result;
}

reader 是一個被 FileReader 工廠new(做)出來的工具,
reader. 後面的其實都使在使用工具本身的功能,
所以存取它內部api functionsthis 就是存取工具本身。

用程式化的說法就是:
你在它的hook內調用this就會指向它的instance(實體)

另一個例子是 computedsetter

javascript
// tab切換後VALUE的改變
const tab = computed({
  get: function () {
    return currentTab.value
  },
  set: function (val) {
    tabOnChange.to = val
    tabOnChange.from = this.value
    const tab = onBeforeSwitchTab(val, this.value)
    currentTab.value = tab
    return tab
  },
});

computed中,getter是不會用到this
setter的話則是this會指向當前這個tab的實體
所以vue裡面本身也就有this的概念存在。

Released under the MIT License.