$emit(子组件给父组件传值)

App.vue

<template>
  <div id="app">
    <my-parent></my-parent>
  </div>
</template>

<script>
import MyParent from "./views/Parent";
export default {
  components: {
    MyParent
  }
};
</script>
<style>
</style>

Parent.vue

<template>
  <div>
    <h2>Parent--{{msg}}</h2>
    <my-child v-bind:msg="`from Parent`" @showMsg="showMsg1"></my-child>
  </div>
</template>

<script>
import MyChild from "./Child";
export default {
  components: {
    MyChild
  },
  data() {
    return {
      msg: ""
    };
  },
  methods: {
    showMsg1(val) {
      this.msg = val;
    }
  }
};
</script>

<style>
</style>

Child.vue

<template>
  <div>
    <h2>Child--{{msg}}</h2>
    <button @click="passMsg">给父组件传值</button>
  </div>
</template>

<script>
export default {
  props: {
    msg: {
      type: String,
      default: ""
    }
  },
  methods: {
    passMsg() {
      this.$emit("showMsg", "from Chlid");
    }
  }
};
</script>

<style>
</style>

猜你喜欢

转载自www.cnblogs.com/xl4ng/p/12591658.html