2020/03/31

[Vue] 如何轉換 jQuery 全域的 click 事件到 Vue 的相對處理方試

前言

採用 jQuery 引用 $(document).click() 的來監聽整份文件的點擊事件

文件內有其他子項目的點擊處理 $('.myButton').click()

那麼以 Vue 的相對處理方式為何? (範例為 Vue 2.x 版本)

監聽事件

在 mounted 加入 document.addEventListener, 事件為 click, callback 為在 Vue 的定義的 onClick 方法

document.addEventListener('click', this.onClick);

在 Vue 的使用如下

new Vue({
  ...
  methods: {
    onClick() {},
    buttonClick() {}
  }
  mounted() {
    document.addEventListener('click', this.onClick);
  },
  beforeDestroy() {
    document.removeEventListener('click', this.onClick);
  },
  ...
});

注意在 HTML 的 Vue click 事件, 需要加上 .stop (它等同於 event.stopPropagation())

這會防止觸發它以外的事件

<button @click.stop="buttonClick">點我</button>

Vue 的 Event Modifiers 除了常用的 .prevent (等同於 event.preventDefault()) 及上面提及的 .stop 之外

還有 .capture, .self, .once, .passive 等事件修飾符

詳細文件可以參考 Event Handling

參考連結

2020/03/16

[TypeScript] 解決 TS2300: Duplicate identifier 'IteratorResult' 錯誤問題

今天在做 VS Code 套件編譯時出現以下錯誤訊息: Duplicate identifier 'IteratorResult'

有 2 個 *.d.ts 檔案定義相沖突

Starting compilation in watch mode...

../../../npm/node_modules/typescript/lib/lib.es2015.iterable.d.ts:41:6 - error TS2300: Duplicate identifier 'IteratorResult'.

41 type IteratorResult<t, treturn="any"> = IteratorYieldResult<t> | IteratorReturnResult<treturn>;
        ~~~~~~~~~~~~~~

  node_modules/@types/node/index.d.ts:74:11
    74 interface IteratorResult<t> { }
                 ~~~~~~~~~~~~~~
    'IteratorResult' was also declared here.

node_modules/@types/node/index.d.ts:74:11 - error TS2300: Duplicate identifier 'IteratorResult'.

74 interface IteratorResult<t> { }
             ~~~~~~~~~~~~~~

  ../../../npm/node_modules/typescript/lib/lib.es2015.iterable.d.ts:41:6
    41 type IteratorResult<t, treturn="any"> = IteratorYieldResult<t> | IteratorReturnResult<treturn>;
            ~~~~~~~~~~~~~~
    'IteratorResult' was also declared here.

Found 2 errors. Watching for file changes.

解決方法

tsconfig.jsoncompilerOptions 區塊加上以下設定, 再重新執行編譯

透過直接跳過 Library 的檢查, 因為它不在我程式碼的控制範圍內, 把它排除即可

  "skipLibCheck": true,