仅当单击该元素时,如何在自定义 vue 指令 运行 中创建逻辑?

how to make the logic inside a custom vue directive run only when that element is clicked on?

现在,我连接到任何元素的指令在页面加载时执行。 这不是我想要的。我希望指令 运行 单击该元素。 我该如何处理这样的事情?

  directives: {
            'new-dir': {
                bind(el, binding, vnode) {
                    el.style.cursor = "pointer";
                    console.log(vnode);
                    if(vnode.tag == 'div'){
                                ...something       }
                    else if(vnode.tag == 'a') {
                      console.log("its a link and clicked");
                      if(vnode.data.attrs.target == "_blank"){
                        console.log("external link");
                      } else{
                        console.log("internal link");
                      }
                    } else if(vnode.tag == 'input') {
                       console.log("its an input ");
                       console.log("type = " + vnode.data.attrs.type)
                       console.log("placeholder = " + vnode.data.attrs.placeholder);
                    }
                }
            },
  }

指令 必须 绑定到元素和当时的指令代码 运行s。

如果您想在点击处理程序中 运行 执行特定逻辑,则需要注册一个

directives: {
  "new-dir": {
    bind: el => {
      el.style.cursor = "pointer"
    },
    inserted: (el, binding, vnode) => {
      // store a reference to the click handler on the element
      // this is primarily so you can remove it later
      el.newDirClickHandler = e => {
        console.log(vnode);
        if (vnode.tag == 'div') {
          // something
        }
        if (vnode.tag == 'a') {
          console.log("its a link and clicked");
          if (vnode.data.attrs.target == "_blank") {
            console.log("external link");
          } else {
            console.log("internal link");
          }
        }
        if (vnode.tag == 'input') {
          console.log("its an input ");
          console.log("type = " + vnode.data.attrs.type)
          console.log("placeholder = " + vnode.data.attrs.placeholder);
        }
      }

      // register the click handler
      el.addEventListener("click", el.newDirClickHandler)
    },
    unbind: el => {
      // unregister the click handler
      el.removeEventListener("click", el.newDirClickHandler)
    }
  }
}