0

I have some problem about component $emit

This is my child component:

<template>
<div class="input-group mb-3 input-group-sm">
        <input v-model="newCoupon" type="text" class="form-control" placeholder="code">
        <div class="input-group-append">
          <button class="btn btn-outline-secondary" type="button" @click="addCoupon">comfirm</button>
        </div>
      </div>
</template>
<script>
export default {
  props: ["couponcode"],
  data() {
    return {
      newCoupon: this.couponcode
    };
  },
  methods: {
    addCoupon() {
      this.$emit("add", this.newCoupon);
    }
  }
};
</script>

This is parent component

<template>
  <div>
<cartData :couponcode="coupon_code" @add="addCoupon"></cartData>
</div>
</template>

<script>
import cartData from "../cartData";
export default {
  components: {
    cartData
  },
  data() {
  return {
   coupon_code: ""
  }
 },
 methods:{
   addCoupon() {
      const api = `${process.env.API_PATH}/api/${
        process.env.CUSTOM_PATH
      }/coupon`;
      const vm = this;
      const coupon = {
        code: vm.coupon_code
      };
      this.$http.post(api, { data: coupon }).then(response => {
        console.log(response.data);
      });
    },
 }
}
</script>

When I click the 'confirm' button,the console.log display 'can't find the coupon' 。 If I don't use the component,it will work 。

What is the problem? It's about emit?

milesyang
  • 3
  • 1
  • Since you assign the prop in the data attribute, my first guess is that it is undefined. Why do you have a component receive a coupon code through a prop and have it send back the same thing through an event? – Sumurai8 Apr 06 '19 at 08:27
  • why aren't you getting the coupon from `addCoupon(coupon)`, as a parameter? – Chamara Abeysekara Apr 06 '19 at 08:33

1 Answers1

0
addCoupon() {
  this.$emit("add", this.newCoupon); // You emitted a param
}
// then you should use it in the listener
addCoupon(coupon) { // take the param
  const api = `${process.env.API_PATH}/api/${
    process.env.CUSTOM_PATH
  }/coupon`;
  const coupon = {
    code: coupon // use it
  };
  this.$http.post(api, { data: coupon }).then(response => {
    console.log(response.data);
  });
},

Cloud Soh Jun Fu
  • 1,456
  • 9
  • 12