如何将作为后端响应的数据传递给 vue.js 中的另一个组件?

问题描述

我正在开发一个页面,负责下订单 Cart.vue,其中包含两个 api 调用 handleMail() 方法正在发送电子邮件生成一个 orderID,我正在像这样的网络部分从后端收到响应.

   { 
     "message":"order created successfully","orderID":87450588
   } 

我正在捕获那个 orderID 并存储为一个 orderNumber,现在我想将该 orderNumber 传递给另一个名为 orderPlace.vue 的组件,并且我想在模板部分中显示该 orderNumber。为此我正在创建事件总线它不是正在工作,请帮我将 orderNumber 传递给另一个组件...

Cart.vue

<template>
<div class="main">

    <div class="first-section">
        <div class="content">
            <h5>My Cart({{books.length}})</h5>
        </div>
        <div v-for="book in books" :key="book.id" class="container">

            <div class="mid-section">
                <img class="img-section" v-bind:src="book.file" alt="not found">
                <p class="title-section">{{book.name}}</p>
            </div>
            <div class="author-section">
                <p class="author-name">by {{book.author}}</p>
            </div>
            <div class="price-section">
                <h6>Rs.{{book.price}}</h6>
            </div>
            <div class="icons">
                <i class="fas fa-minus-circle"></i>
                <input class="rectangle" value=1>
                <i class="fas fa-plus-circle"></i>
            </div>
        </div>
        <div class="btn-grps">
            <button class="btn" v-on:click="flip()" v-if="hide==true" type="submit">Place Order</button>
        </div>
    </div>
    <div class="second -section">
        <div class="details-Box">
            <input type="text" v-if="hide==true" class="initial-btn" placeholder="Customer Details" />
        </div>
        <div v-if="hide==false" class="fill-details">
            <form @submit.prevent="" class="address">
                <h4 class="heading">Customer Details</h4>
                <div class="name">
                    <input type="name" required pattern="[A-Za-z]{3,10}" v-model="name">
                    <label class="label">Name</label>
                </div>

                <div class="name">
                    <input type="text" required v-model="phoneNumber">
                    <label class="label">Phone Number</label>
                </div>
                <div class="pin">
                    <input type="text" required v-model="pincode">
                    <label class="label">PinCode</label>
                </div>
                <div class="pin">
                    <input type="text" required v-model="locality">
                    <label class="label">Locality</label>
                </div>
                <div class="address-block">
                    <input class="address" type="text" required v-model="address">
                    <label id="Add" class="label">Address</label>
                </div>
                <div class="city-landMark">
                    <input type="text" required v-model="city">
                    <label class="label">City/Town</label>
                </div>
                <div class="city-landMark">
                    <input type="text" required v-model="landmark">
                    <label class="label">LandMark</label>
                </div>
                <div class="Radio-Buttons">
                    <p>Type</p>
                    <div class="radio-btns flex-container">
                        <div>
                            <input type="radio" id="Home" value="Home" name="type" v-model="type">
                            <div class="first-radio"> <label class="home" for="Home">Home</label></div>
                        </div>

                        <div>
                            <input class="work-round" type="radio" id="Work" value="Work" name="type" v-model="type">
                            <div class="second-radio"> <label for="Work" class="work-label">Work</label></div>
                        </div>

                        <div>
                            <input class="other-round" type="radio" id="Other" value="Other" name="type" v-model="type">
                            <div class="third-radio"><label class="other-label" for="Other">Other</label></div>
                        </div>
                    </div>

                    <div class="btn-continue">
                        <button type="submit" @click="handlesubmit();handleMail();" class="continue">continue</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
</template>

<script>
import service from '../service/User';
import { EventBus } from "./event-bus.js";
export default {
   created() {
        if (localStorage.getItem("reloaded")) {
            localStorage.removeItem("reloaded");
        } else {
            localStorage.setItem("reloaded","1");
            location.reload();
        }
        service.userdisplayCart().then(response => {
            this.books = response.data;
        })
    },data() {
        return {
            flag: true,hide: true,booksCount: 0,name: '',phoneNumber: '',pincode: '',locality: '',city: '',address: '',landmark: '',type: '',books: [],cart:'MyCart',nameField:'Name',phoneField:'Phone Number',pincodeField:'PinCode',AddressField:'Address',localityField:'Locality',cityField:'CityTown',landmarkField:'LandMark',orderNumber:''
        }
    },methods: {
        flip() {
            this.hide = !this.hide;
        },Togglebtn() {
            this.flag = !this.flag;
        },handlesubmit() {
            let userData = {
                name: this.name,phoneNumber: this.phoneNumber,pincode: this.pincode,locality: this.locality,city: this.city,address: this.address,landmark: this.landmark,type: this.type,}
            service.customerRegister(userData).then(response => {
                return response;
            }).catch(error=>{
                alert("invalid customer address");
                return error;
            })
        },// handleMail(){
        //     service.confirmMail().then(response=>{
        //         alert("order placed successfully");
        //          let orderNumber= response.data.orderID;
        //          this.$router.push({path: '/ordersuccess'});
        //          console.log(response);
        //          return orderNumber;
        //     }).catch(error=>{
        //         alert("Error in sending email");
        //         return error;
        //     })
        // }
        handleMail(){
            service.confirmMail().then(response=>{
                alert("order placed successfully");
                 let orderNumber= response.data.orderID;
                 console.log("my num",orderNumber);
                 EventBus.$emit("emitting-order",orderNumber);
                 this.$router.push({path: '/ordersuccess'});
                 console(response);
                return orderNumber;
            })
        },}
}
</script>

<style lang="scss" scoped>
@import "@/styles/Cart.scss";
</style>

OrderPlace.vue

<template>
<div class="order-place">
    <div class="image-container">
        <img src="../assets/success.png" alt="not found" />

    </div>
    <div class="title-container">
        <p>Order placed Successfully</p>
    </div>
    <div class="message-section">
        <p>Hurray!!!your order is confirmed {{orderNumber}} and placed successfully contact us in below details
            for further communication..</p>
    </div>
    <div class="title-section">
        <div class="email-us">
            <p>Email-us</p>
        </div>
        <div class="contact-us">
            <p>Contact-us</p>
        </div>
        <div class="address">
            <p>Address</p>
        </div>
    </div>
    <div class="email-sec">
        <p>admin@bookstore.com</p>
    </div>
    <div class="contact-sec">
        <p>+918163475881</p>
    </div>
    <div class="address-sec">
        42,14th Main,15th Cross,Sector 4,opp to BDA complex,near Kumarakom restaurant,HSR Layout,Bangalore 560034
    </div>
    <div class="button">
        <router-link to="/dashboard" class="btn">Continue Shopping</router-link>
    </div>
</div>
</template>

<script>
import { EventBus } from "./event-bus.js"; 
export default {
    name: 'OrderPlace',data(){
        return{
            successtitle:'Order placed Successfully',adminemailSection:'Email-us',adminContactSection:'Contact-us',adminAddressSection:'Address',adminemail:'admin@bookstore.com',adminMobNum:'+918163475881',orderNumber: ''
        }        
    },mounted() {  
      EventBus.$on("emitting-order",orderNo=> {  
      this.orderNumber = orderNo;
      console.log(`Oh,that's great ${orderNo})`); 
      return orderNo; 
      });  
   }  
}
</script>

<style lang="scss" scoped>
@import "@/styles/OrderPlace.scss";
</style>

event-bus.js

import Vue from 'vue';  
export const EventBus = new Vue();

解决方法

如果您执行发射时 orderPlace.vue 组件未处于活动状态。它无法接收元素。 您可以尝试在localStorage 中注册您的订单号。或者调用orderPlace.vue作为子组件,将订单号传给props