3
话不多说,先看一段代码, 若想直接看结论, 可直接看文章末尾
// test组件, test.vue
<template>
    <div @click="handleClick">click me</div>
</template>

<script>
export default {
 methods: {
     handleClick () {
         console.log('$listeners: ', this.$listeners, ' , log from test')
         this.$emit('customClick')
     },
 }
}
</script>

// 父组件, index.vue
<template>
 <div class="view-user-list">
    // 注意此时点击后 handleTest不会执行
     <test @click="handleTest" @customClick="handleCustomEvent"></test>
     
     // 注意此处会报错
    <div @click.native="handleTest2"></div>
 </div>
</template>

<script>
export default {
    methods: {
         handleTest () {
            console.log('handleTest')
         },

        handleTest2 () {
            console.log('handleTest2')
         },
     }
}
</script>

UI效果如下:
image.png

运行后报错:
image.png

native修饰符只能用在组件上, 不能用在原生标签上

点击click me后  输出

image.png

父组件中的handleTest函数没有被执行, $listeners对象里有click

此时修改父组件, 给事件加上native修饰符


// 父组件, index.vue

<template>
 <div class="view-user-list">
    // 加上native修饰符后, handleTest会执行
    <test @click.native="handleTest" @customClick="handleCustomEvent"></test>
    
    // 注意此处会报错
    <div @click.native="handleTest2"></div>
 </div>
</template>

<script>
export default {
 methods: {
     handleTest () {
        console.log('handleTest')
     },

     handleTest2 () {
        console.log('handleTest2')
     },
 }
}
</script>

点击click me后 输出
image.png

 父组件中的handleTest函数被执行, $listeners对象里没有了click

结论:

**1. native修饰符可以让父组件接收到原生事件, 否则只能接收自定义事件(通过子组件$emit触发, 如上文的customClick事件就是自定义事件)

  1. native修饰符只能用在组件上, 不能用在原生标签上
  2. $listeners不包含有native修饰符的事件**
遇到框架类的问题, 最直接的解决方案就是查阅文档, 此处献上链接

https://cn.vuejs.org/v2/guide...

https://cn.vuejs.org/v2/api/#...


莲伊
14 声望0 粉丝