Vue使用props和emit父子组件通信

2020-09-03 10:24:14 浏览数 (1)

子组件获取父组件的值和方法

在components创建一个poster组件

代码语言:javascript复制
<template>
  <div></div>
</template>

<script>
export default {
  name: "poster",
  data() {
    return {};
  },
  props: ["title", "getrun"], //title用来接收值,getrun接收方法
  mounted() {
    this.getrun();
    console.log(this.title);
  },
  methods: {}
};
</script>

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

代码语言:javascript复制
<template>
  <div class="home">
    <poster :title="title" :getrun="getFa" />
  </div>
</template>

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

export default {
  name: "home",
  components: {
    poster
  },
  data() {
    return {
      title: "父组件传给子组件的值"
    };
  },
  methods: {
    getFa() {
      console.log("父组件传给子组件的方法");
    }
  }
};
</script>

父组件获取子组件的值和方法

子组件

代码语言:javascript复制
<template>
  <div>
    <button @click="getSon()">子组件向父组件通信</button>
  </div>
</template>

<script>
export default {
  name: "poster",
  data() {
    return {
      sonMsg: "这是子组件的值"
    };
  },
  mounted() {},
  methods: {
    getSon() {
      this.$emit("son", [this.sonMsg, "传递多个值"]);
    }
  }
};
</script>

父组件

代码语言:javascript复制
<template>
  <div class="home">
    <poster @son="getSon" />
  </div>
</template>

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

export default {
  name: "home",
  components: {
    poster
  },
  data() {
    return {};
  },
  methods: {
    getSon(e) {
      console.log(e);
    }
  }
};
</script>

0 人点赞