子组件向父组件传值

2019-08-14  本文已影响0人  最爱喝龙井

子组件向父组件传值

思路:子组件向父组件传值,可以通过调用父组件的方法,来变相的传值

父组件向子组件传递方法

父元素向子元素传递方法可以通过自定义事件属性来实现,在子组件身上自定义事件属性指向父组件的方法,然后通过this.$emit来触发父组件身上的方法。

<div id="app">
        <mycom @myfun='show'></mycom>
    </div>
    <template id="temp">
        <div>
            <input type="button" value="click" @click='change'>
            <h1>hello world</h1>
        </div>
    </template>
    <script>
        var vm = new Vue({
            el: '#app',
            data: {},
            methods: {
                show(data) {
                    console.log(data)
                }
            },
            components: {
                mycom: {
                    template: '#temp',
                    methods: {
                        change() {
                            this.$emit('myfun', '你好')
                        }
                    }
                }
            }
        });
    </script>

子组件向父组件传值

我们可以通过子组件调用父组件中的方法了,所以通过给父组件中的方法传参的方式就可以给父组件传值了

例:

<div id="app">
        <mycom @myfun='show'></mycom>
    </div>
    <template id="temp">
        <div>
            <input type="button" value="click" @click='change'>
            <h1>hello world</h1>
        </div>
    </template>
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                myson: null
            },
            methods: {
                show(data) {
                    this.myson = data;
                }
            },
            components: {
                mycom: {
                    data:function() {
                        return {
                            son: {name: '小宝', age: 3}
                        }
                    },
                    template: '#temp',
                    methods: {
                        change() {
                            this.$emit('myfun', this.son)
                        }
                    }
                }
            }
        });
    </script>
上一篇 下一篇

猜你喜欢

热点阅读