Vue2——父子之间间的调用

1、父组件给子组件传值使用props

父组件:
<div>
    <SonPage  msg="通过props传递值---父=>子" ></SonPage>
    <h1>父组件</h1>
  </div>
子组件
<div :style="{border: '1px solid red'}">
  <h1>子组件</h1>

  <div>我是父组件传入的参数:{{ msg }}</div>
</div>
<script>
export default {
  props: {
    msg: {
      type: String,
    }
  },
  name: "SonPage",
}
</script>

2、父组件调用子组件方法

父组件

使用 this.$refs.sonRef.子组件方法名。父组件在使用子组件时要加ref,上下一致

<template>
  <div>
    <SonPage ref="sonRef" ></SonPage>
    <h1>父组件</h1>
    <button @click="opSon">我要调用子组件</button>
  </div>
</template>

<script>
import SonPage from "@/views/SonPage";

export default {
  name: "pPage",
  components: {SonPage},
 
  methods: {
    opSon() {
      this.$refs.sonRef.ParentOpSon("我是父组件调用子组件方法传入的参数");
    },
  },
}
</script>
子组件
<template>
  <div :style="{border: '1px solid red'}">
    <h1>子组件</h1>
    <div>这里是父组件调用子组件方法传入的参数:{{ msg2 }}</div>
  </div>
</template>

<script>
export default {
  name: "SonPage",
  data() {
    return {
      msg2: ""
    }
  },
  methods: {
    ParentOpSon(parentMsg) {
      this.msg2 = parentMsg;
    },
  },
}
</script>

<style scoped>

</style>
结果:

3、子组件调用父组件方法

父组件

使用子组件标签上加@【子组件的this.$emit中第一个参数名】。方法使用 e就是子组件的参数

<template>
  <div>
    <SonPage @opParent="parentMethod"></SonPage>
    <h1>父组件</h1>
    <div>我是子组件调用父组件方法传入的参数{{ sonMsg }}</div>
  </div>
</template>
<script>
import SonPage from "@/views/SonPage";

export default {
  name: "pPage",
  components: {SonPage},
  data() {
    return {
      sonMsg: ""
    }
  },
  methods: {
    parentMethod(e) {
      console.log(e);
      this.sonMsg = e;
    }
  },

}
</script>

<style scoped>

</style>
子组件

子组件中使用this.$emit("父组件标签上的@的名"," 调用父组件方法的参数")

<template>
  <div :style="{border: '1px solid red'}">
    <h1>子组件</h1>
    <button @click="opParent">我要调用父组件的方法</button>
  </div>
</template>

<script>
export default {
  name: "SonPage",
  data() {
    return {
      msg2: ""
    }
  },
  methods: {
    opParent() {
      this.$emit("opParent", "我是子组件调用父组件方法传入的参数")
    }
  },
}
</script>

<style scoped>

</style>
结果:

三种传值方法都是比较常用的

整理不全面,多多指教~

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值