组件通信-子传父

<body>
    <div id="app">
        <!-- 3.使用子组件 -->
        <App></App>
    </div>
    <script>
        //全局组件
        //子传父:
        //1.在父组件中绑定自定义事件
        //2.在子组件触发原生的事件,在事件函数通过this.$emit触发自定义的事件

        Vue.component('Child', {
            template: `
                <div>
                    <h3>我是一个子组件</h3>   
                    <h4>{{childData}}</h4> 
                    <input type="text" @input = 'handleInput'/>
                </div>
            `,
            props: ['childData'],
            methods: {
                handleInput(e) {
                    const val = e.target.value;
                    this.$emit('inputHandler', val);
                }
            },
        })

        //1.创建局部组件
        //注意:在组件中这个data必须是一个函数,返回一个对象
        const App = {
            data() {
                return {
                    msg: '我是父组件传进来的值',
                    newVal: ''
                }
            },
            methods: {
                input(newVal) {
                    this.newVal = newVal
                }
            },
            template: `
                <div>
                    <div class="father">
                        数据:{{newVal}}
                    </div>
                    <child :childData = 'msg' @inputHandler = "input"></child>
                </div>
                
            `,
            computed: {

            },
        }

        new Vue({
            el: '#app',
            data: {

            },
            components: {
                //2.挂载子组件
                App
            }
        })
    </script>
</body>

猜你喜欢

转载自www.cnblogs.com/nanjo4373977/p/12903114.html