[js]vue中通過ref獲取到元素,如何給元素綁定點擊事件?

vue中通過ref獲取到元素,如何給元素綁定點擊事件?

ref api

ref 被用來給元素或子組件註冊引用信息。引用信息將會註冊在父組件的 $refs 對象上。

如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;
如果用在子組件上,引用就指向組件實例;

<!-- `vm.$refs.p` will be the DOM node -->
<p ref="p">hello</p>

<!-- `vm.$refs.child` will be the child component instance -->
<child-component ref="child"></child-component>

如何給原生dom綁定click方法?

  mounted() {
    console.log(this.$refs)
    this.$nextTick(() => {
      this.$refs.addCard.addEventListener('click', () => {
        this.drawer = true
      })
    })
  }

如何給vue component綁定click方法?

  mounted() {
    this.$nextTick(() => {
      this.$refs.addCard.$el.addEventListener('click', () => {
        this.drawer = true
      })
    })
  }

如何通過ref觸發方法?

//ref=input
this.$refs.input.click();

如何把該dom用css置頂?

z-index mdn

style='z-index: 3000;position: relative'

如何用v-on綁定事件?

vue中的事件監聽之——v-on vs .$on

v-on                            vm.$on
可監聽普通dom的原生事件         監聽當前實例的自定義事件
可監聽子組件emit的自定義事件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章