vue中的$listeners属性做用

1、当组件的根元素不具有一些DOM事件,可是根元素内部元素具有相对应的DOM事件,那么能够使用$listeners获取父组件传递进来的全部事件函数,再经过v-on="xxxx"绑定到相对应的内部元素上便可。html

  注意:使用.native修饰符的事件,不会体如今$listeners属性上。vue

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>vue测试</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.5.22/dist/vue.js"></script>
  <style>

  </style>
 </head>
 <body>
     <div id="app">
        <base-input
            v-model="username" 
            label="基础输入组件"
            @click.native="handleBaseInputClick"
            v-on:focus="handleBaseInputFocus"
            placeholder="请输入您的名字"
            class="username-input"/>
    </div>
    <script>
        // 注册组件
        // 由于base-input的外层是一个label元素,因此默认状况下使用v-on:focus是无效的,因此须要配合$listeners使用,该属性能够把事件的监听指向组件中某个特定的元素
        // 注意:若是父级的事件添加了.native修饰符,在$listeners中不会体现出来的
        Vue.component('base-input',{
            inheritAttrs: false,
            props: ['label','value'],
            template: `
                <label id="base-label">
                    {{label}}
                    <input v-bind:value="value" v-bind="$attrs" v-on="inputListeners"/>
                </label>
            `,
            data: function() {
                return {
                    
                }
            },
 computed: { inputListeners () { var vm = this
                    return Object.assign({},
                        this.$listeners,
                        {
                            input: function () {
                                vm.$emit('input', event.target.value)
                            },
                            focus: function (event) {
                                vm.$emit('focus', '哈哈哈,onfocus了') } } ) } },
            mounted: function(){
                console.log(`$attrs:`)
                console.log(this.$attrs)
                console.log(`$listeners:`)
                console.log(this.$listeners) // 父级添加的全部属性都在这里
            },
            methods: {
                
            }
        })
        var vm = new Vue({
            el: '#app',
            data: {
                username: ''
            },
            created: function(){
            
            },
            beforeUpdate: function(){
            
            },
            computed: {
                
            },
            beforeUpdate: function () {
                console.log(this.username)
            },
            methods: {
                handleBaseInputFocus: function(ev){
                    console.log(ev)
                },
                handleBaseInputClick: function(ev){
                    console.log(ev.type)
                }
            }
        })
    </script>
 </body>
</html>
相关文章
相关标签/搜索