[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的自定义事件
posted @ 2020-08-27 17:01  mmaotai  阅读(14897)  评论(0编辑  收藏  举报