美文网首页
Vue 子组件传递事件给父组件进行通信

Vue 子组件传递事件给父组件进行通信

作者: GaoEnron | 来源:发表于2020-01-11 20:18 被阅读0次

    子组件和父组件进行通信

    可以通过子组件响应方法函数然后发送事件函数,然后父组件进行相应的事件监听然后做相应的处理操作

    1. 首先创建子组件模板

    <template id="cpn">
            <div>
                <button v-for="item in categories" type="button" @click="btnClick(item)">        {{item.name}}</button>
            </div>
    </template>
    

    2. 注册子组件

    发送事件函数 this.$emit('itemclick', item) 第一个参数发送事件函数,第二参数传递参数

      const cpn = {
                    template: '#cpn',
                    props: ['cmovies', 'cmessage'],
                    data() {
                        return {
                            categories: [
                                {id: 'aaa', name: '热门推荐'},
                                {id: 'bbb', name: '热门推荐1'},
                                {id: 'ccc', name: '热门推荐2'},
                                {id: 'ddd', name: '热门推荐3'},
                                {id: 'eee', name: '热门推荐4'},
                                {id: 'fff', name: '热门推荐5'}
                            ]
                        }
                    },
                        
                    methods: {
                        btnClick(item) {
                            console.log(item.name)
                            /* 发送一个事件,父组件需要监听这个事件 */
                            this.$emit('itemclick', item)
                        }
                    }
                }
    

    3. 创建Vue对象,注册子组件

    使用定义的组件监听发送的事件函数,父组件接收到子组件传递的时间

    <div id="app">
            <h1>{{message}}</h1>
            <cpn @itemclick="cpnClick"></cpn>
    </div>
    
    const app = new Vue({
                    el: "#app",
                    data: {
                        message: "你好啊",
                        cmovies: ["海王", "海贼王", "海尔兄弟"],
                        cmessage: "wode"
                    },
                    components: {
                        cpn
                    },
                    methods: {
                        cpnClick() {
                            console.log("事件传递")
                        }
                    }
                    
                })
    

    相关文章

      网友评论

          本文标题:Vue 子组件传递事件给父组件进行通信

          本文链接:https://www.haomeiwen.com/subject/chybactx.html