VUE基础(一)父子组件通讯

一、新建文件

1.新建文件father.vuechildren.vue放在同意目录下;

二、代码如下:

1.father.vue的代码:

<template>
  <div class="fater">
    <h1>我是父组件</h1>
    <h2>我是childern传过来的数据:{
    
    {
    
    ctofValue}}</h2>
    <children :ftoc="ftocValue" ref="child" @pFunc="pFunc"></children>
  </div>
</template>

<script>
import children from "./children";
export default {
    
    
  components: {
    
    
    children: children
  },
  data() {
    
    
    return {
    
    
      ftocValue: "父传子值",
      ctofValue: "",
      implementValue: "父组件执行子组件方法"
    };
  },
  methods: {
    
    
    pFunc(value) {
    
    
      this.ctofValue = value;
    },
    childrenFun() {
    
    
      this.$refs.child.childFun("父组件执行子组件方法");
    }
  },
  mounted() {
    
    
    this.childrenFun();
  }
};
</script>

<style>
.fater {
    
    
  border: 5px solid red;
}
</style>

2.children.vue的代码:

<template>
  <div class="children">
    <h1>我是子组件</h1>
    <h3>我是father传过来的数据:{
    
    {
    
    ftoc}}</h3>
    <h3>我是father执行子组件的childFun方法传过来的数据:{
    
    {
    
    imValue}}</h3>

  </div>
</template>

<script>
export default {
    
    
  props: {
    
    
    ftoc: String
  },
  data() {
    
    
    return {
    
    
      msg: "子传父值",
      imValue: ""
    };
  },
  methods: {
    
    
    sendMes() {
    
    
      this.$emit("pFunc", this.msg);
    },
    childFun(value) {
    
    
      this.imValue = value;
    }
  },
  mounted() {
    
    
    this.sendMes();
  }
};
</script>

<style>
.children {
    
    
  border: 5px solid red;
}
</style>

三、代码运行网页示例如下:

在这里插入图片描述

四、解析:

本示例演示了,父子组件传值,父组件执行子组件方法,子组件执行父组件方法的输出结果和过程。
父组件给子组件传值:通过在father文件中组件绑定值ftoc传值给子组件,然后子组件通过props接收并输出数据,使子组件可以使用他。
子组件给父组件传值(子组件执行父组件中的方法):通过在father文件中监听事件pFunc然后去执行pFunc,子组件通过$emit去执行pFunc来达到执行父组件事件并传值的效果。
父组件执行子组件的方法:在father页面中给子组件声明ref,通过$ref.(ref的值)来确定执行那个子组件中的方法。

五、有什么问题可以在下面讨论,我会为大家解答。

猜你喜欢

转载自blog.csdn.net/samxiaoguai/article/details/106476342