简单易懂的vue父子组件通信实例

父组件向子组件传递数据是通过prop传递的,子组件传递数据给父组件是通过$emit触发事件来做到的。 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">

    </div>

    <script src="/vue.js"></script>
    <script>
        Vue.component('child', {
            data() {
                return {
                    mymessage: this.params2
                }
            },
            template: `
            <div>
                <input type="text" v-model="mymessage" @input="passData(mymessage)"> </div>
        `,
            props: ['params2'], //得到父组件传递过来的数据
            methods: {
                passData(val) {
                    //触发父组件中的事件
                    this.$emit('sendChildData', val)
                }
            }
        })
        Vue.component('parent', {
            template: `
            <div>
                <p>this is parent compoent!</p>
                <child :params2="params1" v-on:sendChildData="getChildData"></child>
            </div>
        `,
            data() {
                return {
                    params1: 'hello'
                }
            },
            methods: {
                //执行子组件触发的事件
                getChildData(val) {
                    console.log(val)
                }
            }
        })
        var app = new Vue({
            el: '#app',
            template: `
            <div>
                <parent></parent>
            </div>
        `
        })
    </script>
</body>

</html>

代码实现的效果如下:

 以上实例实现的操作是父组件先向子组件传递参数params1,子组件接收到数据后将数据绑定到input中显示在页面,如果input数据发生变化,触发子组件中的passData函数,passData函数的作用是:通过$emit触发sendChildData事件,调用父组件中的打印方法,最后将子组件中的数据打印在控制台。

猜你喜欢

转载自blog.csdn.net/liangmengbk/article/details/88362614