zoukankan      html  css  js  c++  java
  • Vue3 学习笔记05-子组件向父组件,使用$emit方法

    子组件的代码:

    <template>
        <div>
            <h1>this is child component</h1>
            <button @click="toParent">向父组件传值</button>
        </div>
    </template>
     
     
    <script>
    export default {
        data() {
            return {
                data1: '子组件的数据'
            }
        },
        methods: {
            toParent:function() {
                this.$emit('event1', this.data1)
            }
        }
    }
    </script>
     
    <style scoped>
        div {
            border: 1px solid red;
        }
    </style>

    父组件的代码:

    <template>
        <div>
            {{ newData }}
            <child @event1="change($event)"></child>
            
        </div>
    </template>
     
     
    <script>
    import child from './components/Child.vue';
    export default {
        data() {
            return {
                newData: '这是父组件的数据'
            }
        },
        methods: {
            change(data) {
                this.newData = data;
            }
        },
        components: {child}
    }
    </script>
     
    <style>
     
    </style>

    效果图:

    代码解释:
    1、在子组件中,首先需要使用$emit方法,该方法接收2个参数,第一个参数是事件的名称,自己随意定义。第二个参数是需要传递的数据,可以是对象,也可以是字符串类型。$emit是VUE实例中的一个方法,所以前面要加上this,可以在钩子函数中执行,也可以由某个事件触发执行。

    2、在父组件中,程序会查找刚才在子组件中注册的事件名,该事件又有一个方法change,change方法将newData的值改变了。

    参考文献:https://blog.csdn.net/joyvonlee/article/details/90545808

  • 相关阅读:
    axios express设置跨域允许传递cookie
    yarn常用命令指北
    Web代理工具NProxy
    DevOps的了解
    css图片hover放大
    autoprefixer
    谈谈浏览器http缓存
    欢迎使用 MWeb
    优化关键渲染路径CRP
    chrome 61 更新
  • 原文地址:https://www.cnblogs.com/luckyplj/p/15064883.html
Copyright © 2011-2022 走看看