深入了解组件- -- 自定义事件

gitHub地址:https://github.com/huangpna/vue_learn/example里面的lesson09

一 事件名

举例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index1</title>
</head>
<body>
    <div id="app1">
        <my-component v-bind:num="a" v-on:my-event="doSomething"></my-component>  <!--$on(eventName)监听事件-->
    </div>
</body>
<script src="../js/vue.js"></script>
<script>
    Vue.component('my-component',{
        props:['num'],
        template:'<div><p>{{num}}</p><button v-on:click="changeV">自定义事件触发</button></div>',
        methods:{
            changeV:function () {
                let _this = this;
                _this.$emit('my-event');<!--$emit(eventName)触发事件-->
            }
        }
    });
    new Vue({
        el:'#app1',
        data:{
            a:0
        },
        methods:{
            doSomething:function () {
                let _this = this;
                _this.a += 1;
            }
        }
    })
</script>
</html>

事件名不同于组件和prop,不存在任何自动化大小写的转换,而是触发的事件名需要完全匹配监听这个事件所用的名称。

假如说,如果触发一个 camelCase 名字的事件:

this.$emit('myEvent')

这个时候监听这个名字的 kebab-case 版本是不会有任何效果的:

<my-component v-on:my-event="doSomething"></my-component>

并且 v-on 事件监听器在 DOM 模板中会被自动转换为全小写 (因为 HTML 是大小写不敏感的),所以 v-on:myEvent 将会变成 v-on:myevent——导致 myEvent 不可能被监听到。

因此,推荐使用 kebab-case 的事件名。

二 自定义组件的v-model

v-model实现了表单输入的双向绑定,但是我们一般是这样写的:

<input v-model="price">

通过该语句实现price变量与输入值双向绑定

实际上v-model只是一个语法糖,真正实现是这样的:

<input type="text" 
      :value="price" 
      @input="price=$event.target.value">

以上代码分几个步骤:

  1. 将输入框的值绑定到price变量上,这个是单向绑定,意味着改变price变量的值可以改变input的value,但是改变value不能改变price
  2. 监听input事件(input输入框都有该事件,当输入内容时自动触发该事件),当输入框输入内容就单向改变price的值

这样就实现了双向绑定。

举例说明(自定义组件input):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index2</title>
</head>
<body>
    <div id="app2">
        <input-price v-bind:value="price" @input="changeV"></input-price>   <!--在自定义input组件的时候,v-model并不能直接实现双向绑定的效果-->
        <p>{{price}}</p>
    </div>
</body>
<script src="../js/vue.js"></script>
<script>
    /**
     * 自定义一个input组件
     * */
    Vue.component('input-price',{
       props:['value'],
       template:'<div><input type="text" :value="value" @input="changeV($event)"/></div>',
       methods:{
           changeV:function (e) {
               let _this = this;
               _this.$emit('input',e.target.value)
           }
       } 
    });
    new Vue({
        el:'#app2',
        data:{
            price:''
        },
        methods:{
            changeV:function (v) {
                let _this = this;
                _this.price = v;
            }
        }
    })
</script>
</html>

但是像单选框、复选框等类型的输入控件可能会将value特性用于不同的目的,model选项可以用于避免这样的冲突。

举例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index3</title>
</head>
<body>
    <div id="app3">
        <base-checkbox v-model="cstchecked"></base-checkbox>
        {{cstchecked}}
    </div>
</body>
<script src="../js/vue.js"></script>
<script>
    Vue.component('base-checkbox', {
        model: {
            prop: 'checked',//checked与父级cstchecked联动
            event: 'achange' // 事件名随便定义,反正有了model后就可以触发父组件的事件了
        },
        props:{
            checked:{
                type:Boolean
            }
        },
        template:'<div>多选框:<input type="checkbox" v-bind:checked="checked" @change="changeV($event)"></div>',
        methods:{
            changeV:function (e) {
                let _this = this;
                _this.$emit("achange",e.target.checked); //触发父组件的事件,并将值传给 prop: 'checked',从而改变了父级传入的cstchecked
            }
        }
    });
    new Vue({
        el:'#app3',
        data:{
            cstchecked:false
        }
    })
</script>
</html>

这里的cstchecked将会传入这个名为checked的prop。同时当触发一个change事件的时候将会附带一个新的值,这个cstchecked的属性将会被更新。

注意你仍然需要在组件的 props 选项里声明 checked 这个 prop。

三 将原生事件绑定到组件

方法一(举例):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index4</title>
</head>
<body>
    <div id="app4">
        <base-input v-bind:label="label" v-on:focus.native="onFocus"  v-bind:value="value" @input="changr"></base-input>
        {{value}}
    </div>
</body>
<script src="../js/vue.js"></script>
<script>
    Vue.component('base-input',{
        props:['label','value'],
       template:`<label>{{ label }}<input   v-bind="$attrs"  v-bind:value="value"   v-on:input="$emit('input', $event.target.value)"></label>`
    });
    new Vue({
        el:'#app4',
        data:{
            label:'标题',
            value:''
        },
        methods:{
            changr:function (v) {
              this.value = v;
            },
            onFocus:function () {
                console.log('1111');
            }
        }
    })
</script>
</html>

你可能很多时候在一个根元素上都想要直接监听一个原生事件,这个时候你可以用v-on的.native修饰符,在有的时候用这个修饰符是非常有用的,但是在你尝试监听一个类似<input>的非常特定的元素时,这并不是个好主意,比如上述<base-input>组件,他的根元素实际上<label>元素,这时父级的.native监听器将静默失败,并且他也不会产生任何报错,但是onFocus处理函数不会如你预期地被调用。

为了解决这个问题,Vue 提供了一个 $listeners 属性(它是一个对象,里面包含了作用在这个组件上的所有监听器)。

(1)使用 v-on="$listeners" 将所有的事件监听器指向这个组件的某个特定的子元素。

例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index5</title>
</head>
<body>
<div id="app5">
    <base-input :label="label" v-on:focus="onFocus" v-model="value" :value="value" @input="changr"></base-input>
    <p>{{value}}</p>
</div>
</body>
<script src="../js/vue.js"></script>
<script>
    Vue.component('base-input',{
        props:['label','value'],
        template:`<label>{{ label }}<input  v-on="$listeners"  :value="value"  @input="$emit('input', $event)"></label>`
    });
    new Vue({
        el:'#app5',
        data:{
            label:'标题',
            value:''
        },
        methods:{
            changr:function (e) {
                let _this = this;
                _this.value = e.target.value;
            },
            onFocus:function () {
                console.log('获取焦点');
            }
        }
    })
</script>
</html>

(2)对于类似 <input> 的你希望它也可以配合 v-model 工作的组件来说,为这些监听器创建一个类似下述 listeners 的计算属性通常是非常有用的:

例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index4</title>
</head>
<body>
    <div id="app4">
        <base-input v-bind:label="label" v-model="value" v-on:focus="onFocus"  v-on:blur="onBlur"></base-input>
        <p>{{value}}</p>
    </div>
</body>
<script src="../js/vue.js"></script>
<script>
    Vue.component('base-input',{
        props:['label','value'],
       template:`<label>{{ label }}<input   v-bind="$attrs"  v-on="inputListeners" v-bind:value="value"></label>`,
        computed: {
            inputListeners: function () {
                var vm = this
                // `Object.assign` 将所有的对象合并为一个新对象
                return Object.assign({},
                    // 我们从父级添加所有的监听器
                    this.$listeners,
                    // 然后我们添加自定义监听器,
                    // 或覆写一些监听器的行为
                    {
                        // 这里确保组件配合 `v-model` 的工作
                        input: function (event) {
                            vm.$emit('input', event.target.value)
                        }
                    }
                )
            }
        }
    });
    new Vue({
        el:'#app4',
        data:{
            label:'标题',
            value:''
        },
        methods:{
            onFocus:function () {
                console.log('获取焦点');
            },
            onBlur:function () {
                console.log('失去焦点');
            }
        }
    })
</script>
</html>

现在 <base-input> 组件是一个完全透明的包裹器了,也就是说它可以完全像一个普通的 <input> 元素一样使用了:所有跟它相同的特性和监听器的都可以工作。

三  .sync 修饰符(2.3.0+ 新增)

在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以修改父组件,且在父组件和子组件都没有明显的改动来源。

这也是为什么我们推荐以 update:myPropName 的模式触发事件取而代之。举个例子,在一个包含 title prop 的假设的组件中,我们可以用以下方法表达对其赋新值的意图:

this.$emit('update:title', newTitle)

然后父组件可以监听那个事件并根据需要更新一个本地的数据属性。例如:

<text-document
  v-bind:title="doc.title"
  v-on:update:title="doc.title = $event"
></text-document>

为了方便起见,我们为这种模式提供一个缩写,即 .sync 修饰符:

<text-document v-bind:title.sync="doc.title"></text-document>

注意带有 .sync 修饰符的 v-bind 不能和表达式一起使用,取而代之的是,你只能提供你想要绑定的属性名,类似 v-model。

当我们用一个对象同时设置多个 prop 的时候,也可以将这个 .sync 修饰符和 v-bind 配合使用:

<text-document v-bind.sync="doc"></text-document>

这样会把 doc 对象中的每一个属性 (如 title) 都作为一个独立的 prop 传进去,然后各自添加用于更新的 v-on 监听器。

注意:将 v-bind.sync 用在一个字面量的对象上,例如 v-bind.sync=”{ title: doc.title }”,是无法正常工作的,因为在解析一个像这样的复杂表达式的时候,有很多边缘情况需要考虑。

 以下为代码举例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index6</title>
    <style>
        #app6>div>p{
            width:500px;
            height:200px;
            border:1px solid red;
        }
    </style>
</head>
<body>
    <div id="app6">
        <text-document :show.sync="ase"></text-document>
        <button @click="openDiv">打开</button>
    </div>
</body>
<script src="../js/vue.js"></script>
<script>
    /**
     * .sync 修饰符
    * */
    Vue.component('text-document',{
        props:['show'],
        template:'<div v-if="show"><p>默认初始值是{{show}},所以是显示的<button @click.stop="closeDiv">关闭</button></p></div>',
        methods:{
            closeDiv:function () {
                let _this = this;
                _this.$emit('update:show', false)
            }
        }

    });
    new Vue({
        el:'#app6',
        data:{
            ase:true
        },
        methods:{
            openDiv:function () {
               let _this = this;
               _this.ase = !_this.ase;
            }
        }
    })
</script>
</html>

越往后面学习,感觉有些知识点掌握的比较模糊,希望在所有文档学习忘之后能够自己搭建vue+webapck框架,然后一一写一些组件验证一下(多巩固巩固!)。

原文地址:https://www.cnblogs.com/1156063074hp/p/10078047.html