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>
    

  • 相关阅读:
    Half Nice Years Gym
    LCM from 1 to n
    Educational Codeforces Round 70 (Rated for Div. 2)
    Rating(概率DP) HDU
    Josephina and RPG(概率DP) ZOJ
    数据结构实验之串二:字符串匹配(字符串哈希)
    点分治——入门学习笔记
    使用ASP.NET Core 3.x 构建 RESTful API P15 处理故障
    使用ASP.NET Core 3.x 构建 RESTful API P13 P14 获取父子关系的资源
    使用ASP.NET Core 3.x 构建 RESTful API P11 P12 ActionResult of T 以及 AutoMapper
  • 原文地址:https://www.cnblogs.com/lori/p/13195127.html
Copyright © 2011-2022 走看看