Vue使用ref父子组件通信

时间:2022-07-24
本文章向大家介绍Vue使用ref父子组件通信,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

创建一个子组件

<template>
  <div>
    <button @click="getParent()">获取父组件信息</button>
  </div>
</template>
<script>
export default {
  name: "poster",
  data() {
    return {
      sonMsg: "这是子组件的值"
    };
  },
  mounted() {},
  methods: {
    getSon() {
      console.log("这是子组件的方法");
    },
    getParent() {
      //子组件通过$parent获取父组件的方法和值
      this.$parent.getFa();
      console.log(this.$parent.faMsg);
    }
  }
};
</script>

创建一个父组件,把子组件引入到父组件中去

<template>
  <div class="home">
    <poster ref="poster" />
  </div>
</template>

<script>
import poster from "@/components/poster.vue";

export default {
  name: "home",
  components: {
    poster
  },
  data() {
    return {
      faMsg: "这是父组件的值"
    };
  },
  mounted() {
    // 获取到子组件的值和方法
    this.$refs.poster.getSon();
    console.log(this.$refs.poster.sonMsg);
  },
  methods: {
    getFa() {
      console.log("这是父组件的方法");
    }
  }
};
</script>