zoukankan      html  css  js  c++  java
  • vue子组件调用父组件的方法

    一、$parent

      父组件

    <template>
      <div>
        <child></child>
      </div>
    </template>
    <script>
      import child from './child';
      export default {
        components: {
          child
        },
        methods: {
          fatherMethod(str) {
            console.log(str);
          }
        }
      };
    </script>

      子组件

    <template>
      <div>
        <button @click="childMethod">点击</button>
      </div>
    </template>
    <script>
      export default {
        methods: {
          childMethod() {
            this.$parent.fatherMethod('hello');
          }
        }
      };
    </script>

    二、props

      父组件

    <template>
      <div>
        <child :fatherMethod="fatherMethodOther"></child>
      </div>
    </template>
    <script>
      import child from './child';
      export default {
        components: {
          child
        },
        methods: {
          fatherMethodOther(str) {
            console.log(str);
          }
        }
      };
    </script>

      子组件

    <template>
      <div>
        <button @click="childMethod">点击</button>
      </div>
    </template>
    <script>
      export default {
        props: {
          fatherMethod: {
            type: Function,
            default: null
          }
        },
        methods: {
          childMethod() {
            if (this.fatherMethod) {
              this.fatherMethod('hello');
            }
          }
        }
      };
    </script>

    三、$emit

      父组件

    <template>
      <div>
        <child @fatherMethod="fatherMethodOther"></child>
      </div>
    </template>
    <script>
      import child from './child';
      export default {
        components: {
          child
        },
        methods: {
          fatherMethodOther(str) {
            console.log(str);
          }
        }
      };
    </script>

      子组件

    <template>
      <div>
        <button @click="childMethod">点击</button>
      </div>
    </template>
    <script>
      export default {
        methods: {
          childMethod() {
            this.$emit('fatherMethod', 'hello');
          }
        }
      };
    </script>

    参考链接:https://www.jianshu.com/p/3b2651529dad

  • 相关阅读:
    python 正则表达式 (重点) re模块
    python 异常处理
    面向对象 反射 特殊方法
    3. 容器备份与迁移
    2. Docker部署tomcat, nginx, redis,及docker私有仓库
    1. Docker快速入门(仓库,镜像,容器)
    Linux部署项目 shell脚本启动 及 Centos7开放指定端口
    nginx快速入门
    linux安装mysql8(完整图文笔记)
    Redis主从架构核心原理
  • 原文地址:https://www.cnblogs.com/helloNico/p/12427654.html
Copyright © 2011-2022 走看看