zoukankan      html  css  js  c++  java
  • vue~父组件与子组件的交互

    我们在进行vue开发时会将公共的部分进行抽象,然后生成一个独立的组件,这个组件可以被其它页面引用,如果希望有交互的动作就设计到了值的传递,或者方法的回调等问题,这一次我们主要来说一下父组件和子组件的交互。

    值的传递

    子组件,通过定义了prods,然后可以实现从父组件向子组件的传递:

      <template>
      <div id="app">
        这是自定义的组件:{{myMessage}}
        <button @click="childClick">调用父组件的方法</button>
      </div>
    </template>
    <script>
    export default {
      name: "testComponent",
      props: ["myMessage"],
      data() {
        return {
          message: "hello world",
          myNum: 37,
          myStr: "lind"
        };
      },
      methods: {
        childClick() {
           console.log("调用childClick");
          this.$emit("abcClick", this.myNum, this.myStr);
        }
      }
    };
    </script>
    

    父组件/页面,直接为这个prods赋值即可,注意如果JS里props名称是小驼峰,在html需要用中线来代替

        <testComponent my-message="hello"></testComponent> 
    <script>
    import testComponent from "@/components/testComponent";
    export default {
      name: "test-grammer",
      props: {
        //接收父组件传递过来的参数
      },
      components: {
        testComponent
      }
    }
    </script>
    

    方法的传递/回调

    在父页面绑定子组件的方法,然后子组件在某个时机去触,这就形成了在子组件里调用父组件的方法,使用了$emit来实现

     <button @click="childClick">调用父组件的方法</button>
    <script>
    export default {
      name: "testComponent",
      methods: {
        childClick() {
          this.$emit("abcClick", this.myNum, this.myStr);
        }
      }
    };
    </script>
    

    在父页面中去绑定这个abcClick事件就可以了,当在子组件调用这个childClick事件时,绑定了abcClick的方法将会被一起回调

    <testComponent  @abcClick="sayHello"></testComponent>
    <script>
    import testComponent from "@/components/testComponent";
    export default {
      name: "test-grammer",
      methods: {
        sayHello(Num, Str) {
          console.log("hello world~~" + Num + Str);
        }
      },
    };
    </script>
    

  • 相关阅读:
    nmap扫描工具
    cobbler全自动批量安装部署linux
    使用ngxtop实时监控nginx
    Nginx 错误汇总
    定制sudo的密码保持时间以及如何不需要密码
    解决eclipse中出现Resource is out of sync with the file system问题
    log4j:ERROR Category option " 1 " not a decimal integer.错误解决
    properties文件中中文不能显示或者中文乱码
    Log4j使用总结
    eclipse, Log4j配置(真心的详细~)
  • 原文地址:https://www.cnblogs.com/lori/p/13195127.html
Copyright © 2011-2022 走看看