zoukankan      html  css  js  c++  java
  • Vue——父子组件通信

    父子组件之间的通信属于传递私有数据,比较容易理解

    实现方式

    • 父组件向子组件传值

      • 直接在子组件的标签上绑定属性
      • 子组件声明 props 来接收父组件传值的属性
    • 子组件向父组件传值

      • 直接在子组件的标签上绑定方法
      • 子组件通过 $emit 方法调用父组件绑定过来的方法,并通过传递参数的形式达到传值的目的,这里的参数个数可以是多个,不固定

    具体案例

    • props

      <!--父组件-->
      <template>
          <span>父组件:</span>
          <input type="text" v-model="pVal">
          <son :textP='pVal'></son>
      </template>
      <script>
      export default {
        data() {
          return {
            pVal: 12
          };
        }
      </script>
      
      <!--子组件 son-->
      <template>
          <div class="props">
              <span>子组件:</span>
              <input type="text" v-model="textP">
          </div>
      </template>
      <script>
      export default {
        props: ["textP"]
      };
      </script>
      
    • $emit

      <!--父组件-->
      <template>
          <son @pMethod='show'></son>
      </template>
      <script>
      export default {
        data() {
          return {
            pVal: 12
          };
        },
        methods: {
         	show(data) {
            this.pVal = data;
          }
        }
      };
      </script>
      
      <!--子组件-->
      <template>
          <div class="props">
              <span>子组件:</span>
              <button @click="change">点击改变父组件的值</button>
          </div>
      </template>
      <script>
      export default {
        methods: {
          change() {
            this.$emit("pMethod", 19);
          }
        }
      };
      </script>
      

    总结分析

    • 关于子组件向父组件传值,其形式上与 jsonp 类似,服务器将想要传递的数据通过一个 callback 方法传参的形式最终达到跨域传值的目的

    • 其实这样的形式也十分类似 winform 里面的不同窗口之间的传值,也是通过方法传递参数

  • 相关阅读:
    洛谷 P3040 [USACO12JAN]贝尔分享Bale Share
    洛谷 P1994 有机物燃烧
    洛谷 P3692 [PUB1]夏幻的考试
    洛谷 P2117 小Z的矩阵
    洛谷 P1154 奶牛分厩
    洛谷 P1718 图形复原
    洛谷 P1900 自我数
    洛谷 P1964 【mc生存】卖东西
    洛谷 P1123 取数游戏
    hdu_2844_Coins(多重背包)
  • 原文地址:https://www.cnblogs.com/cnloop/p/9278984.html
Copyright © 2011-2022 走看看