Vue组件中自定义事件

    当我们需要在操作组件后引起组件之外的元素发生变化时,就需要是这里的内容。比如:当选中书后,自动显示您选中的书名。其中书籍列表是使用组件写的。显示选中书籍名是在组件之外。
    在添加事件的时候需要注意一下事项:
    1、在定义组件时`Vue.component(组件名,{props(参数),template(html代码),methods(子组件中的事件),}`,
    在子组件中正常调用该事件,但是在需要与父组件联系时,需要在该事件中写第2条的信息。
    2、在需要出发事件的时候,调用`this.emit('事件的名称',参数(可以是多个))
    3、在使用这个组件的时候,绑定下事件,语法和之前绑定是一样的,比如:@father-click="FatherClick",
    @事件名称=父组件中事件。
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <title>Vue组件中自定义事件</title>
</head>

<body>
    <div id="app">
        <child-template v-for="book in books" :book="book" @father-click="FatherClick"></child-template>
        <p>你选中了:{{checkbooks}}</p>
    </div>
    <script>
        Vue.component("child-template", {
            props: ['book'],
            template: `
            <div>
                <label>{{book.title}}</label>
                <input type="checkbox" @click="onCheck" >
            </div>
        `,
            methods: {
                onCheck() {
                    // 将子组件与父组件联合起来
                    this.$emit('father-click', this.book)
                }
            },
        })
        new Vue({
            el: "#app",
            data: {
                books: [{
                        title: '水浒传',
                    },
                    {
                        title: '三国演义',
                    },
                    {
                        title: '西游记',
                    },
                    {
                        title: '红楼梦',
                    },
                ],
                checkbooks: []
            },
            methods: {
                'FatherClick'(bookName) {
                    // indexOf:获取某个元素在数组中的位置,如果返回值为非负数,那么就是存在,就是下标
                    // 否则,代表这个元素在数组中不存在
                    let booknameIndex = this.checkbooks.indexOf(bookName.title)
                    if (booknameIndex >= 0) {
                        this.checkbooks.splice(booknameIndex, 1)
                    } else {
                        this.checkbooks.push(bookName.title)
                    }
                }
            }
        })
    </script>
</body>

</html>

 

posted @ 2020-02-21 16:36  xsan  阅读(2467)  评论(0编辑  收藏  举报