vue子到父之间的传值 2018

2018-11-05  本文已影响0人  小帅_Cs

1.子到父之间的传值通过在子组件上绑定自定义事件(<v-child @index = 'huoqu'></v-child>),在子组件中事件中通过this.$emit("index",this.str)    this.$emit("要推送给那个事件",要推送的内容)  然后在父组件中通过事件"huoqu"来接受参数,"huoqu"事件中的参数,就是子组件传值传过来的参数:

huoqu(msg){

    msg就是子组件传过来的参数        这个函数写在父组件中

};

例子如下:

<div id="out">

        <v-parent></v-parent>

</div>

<template id="parent">

    <div>

        <h3>父组件</h3>

        <p>{{str}}</p>

        <hr>

        <v-child @index = 'huoqu'></v-child>

    </div>

</template>

<template id="child">

    <div>

        <h3>子组件</h3>

        <p>{{str}}</p>

        <button @click="tap()">发送数据</button>

    </div>

</template>

</body>

<script type="text/javascript">

    var vm = new Vue({

        el:'#out',

        components:{

        'v-parent':{

            template:'#parent',

            data:function(){

                return{

                    str:''

                    }

            },

methods:{

            huoqu:function(msg){

                    this.str = msg

                    }

                },

components:{

    'v-child':{

        template:'#child',

    data:function(){

            return{

                str:'我是子组件'

                }

        },

methods:{

    tap(){

        this.$emit('index',this.str)

            }

        }

    }

}

}

}

})

上一篇 下一篇

猜你喜欢

热点阅读