vue 子组件给父组件传值

子组件给父组件传值的关键内容--在父组件中使用子组件,在使用时自定义事件类型和事件函数--在子组件中需要定义事件来定义事件类型--在子组件的methods中的事件函数中用this.$emit()方法操作事件类型--在父组件的methods中操作自定义的事件函数

 

   <div id='app'>
        <son @father="fatherdata()"></son>
    </div>

    <template id="son">
        <div>
            <button @click="changefather">点击传值</button>
        </div>
    </template>
    <script>
        Vue.component("son", {
            template: son,
            methods: {
                changefather() {
                    this.$emit("father", "要传的数据")
                }
            }
        })
    </script>
    <script>
        const vm = new Vue({
            el: '#app',
            methods: {
                fatherdata(data) {
                    console.log(data); //结果:传过来的数据
                }
            }
        })
    </script>

 

posted @ 2021-01-04 20:49  迷路的搬砖人  阅读(66)  评论(0)    收藏  举报