JS——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 里面的不同窗口之间的传值,也是通过方法传递参数

猜你喜欢

转载自www.cnblogs.com/cnloop/p/9278984.html