利用自定义绑定事件来 传值 实现子传父数据,父传子数据

Posted blccy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用自定义绑定事件来 传值 实现子传父数据,父传子数据相关的知识,希望对你有一定的参考价值。

例子

用$emit  绑定自定义事件 $emit("receive",item) 然后再触发父子的自定义事件 执行函数  v-on:receive="changeValueHandle"    changeValueHandle(value){this.val = value;}  item 就是要传入父级的值,value就是接收 item的

<body>
        <div id="app">
            <div style="float: left;">
                <h2>自定义的下拉框</h2>
                <custom-select btn="查询" v-bind:list="list1"></custom-select>
            </div>
            <div style="float:left;">
                <h2>自定义的下拉框2</h2>
                <custom-select btn="搜索" v-bind:list="list2"></custom-select>
            </div>
        </div>
        <script>
        /*var obj = {
                    selectShow:false
                }*/
            //注册组件
            Vue.component("custom-select",{
                data:function(){
                    return {
                        selectShow:false,
                        val:""
                    };
                },
                props:["btn","list"],
                template:`<section class="warp">
                    <div class="searchIpt clearFix">
                        <div class="clearFix">
                            <input type="text" class="keyWord" :value="val" @click="selectShow = !selectShow" />
                            <input type="button" :value="btn">
                            <span></span>
                        </div>
                        <custom-list
                            v-show="selectShow"
                            :list="list"
                            v-on:receive="changeValueHandle"
                        ></custom-list>
                    </div>
                </section>`,
                methods:{
                    changeValueHandle(value){
                        //alert("我被触发了,值为:"+value);
                        this.val = value;
                    }
                }
            })
            Vue.component("custom-list",{
                props:["list"],
                template:`<ul class="list">
                            <li v-for="item of list" @click="selectValueHandle(item)">{{item}}</li>
                        </ul>`,
                methods:{
                    selectValueHandle:function(item){
                        //在子组件中有交互
                        //告知父级,改变val的值,需要出发一个自定义事件

                        this.$emit("receive",item);
                    }
                }
            })      

            new Vue({
                el:"#app",
                data:{
                    list1:["北京","上海","杭州"],
                    list2:["17-02-17","17-02-18","17-02-19"]
                }
            });
        </script>
    </body>

以上是关于利用自定义绑定事件来 传值 实现子传父数据,父传子数据的主要内容,如果未能解决你的问题,请参考以下文章

Vue组件间传值(超全,跨代)父传子,子传父,爷传孙,孙传爷,保姆级讲解

vue的组件通讯 父传子 -- 子传父-- 兄弟组件的传值 vue的组件传值

React传值(子传父,父传子)

vue组件传值(超简单易懂)

vue组件父传子、子传父、兄弟组件之间传值

vue 组件通信 (子传父 , 父传子 , 兄弟通信)