VUE basics (1) parent-child component communication

1. Create a new file

1. Create a new file father.vueand children.vueput it in the agreed directory;

2. The code is as follows:

1. father.vueThe code:

<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.vueThe code:

<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>

3. The example of the code running web page is as follows:

insert image description here

4. Analysis:

This example demonstrates that parent-child components pass values, the parent component executes the method of the child component, and the child component executes the output result and process of the method of the parent component.
The parent component passes the value to the child component: pass the value to the child component through fatherthe component binding value in the file ftoc, and then the child component propsreceives and outputs the data, so that the child component can use him.
The child component passes the value to the parent component (the child component executes the method in the parent component): by fatherlistening to the event in the file pFuncand then executing it pFunc, the child component achieves the effect of executing the parent component event and passing the value by $emitexecuting it . The parent component executes the method of the child component: declare the child component in the page , and determine the method in which child component to execute by ( value).pFunc
fatherref$ref.ref

5. If you have any questions, you can discuss them below, and I will answer them for you.

Guess you like

Origin blog.csdn.net/samxiaoguai/article/details/106476342