Django项目中Vue组件间数据传递问题(非Vuex方案)
Got it, let's tackle this without Vuex—we can leverage Vue's native parent-child communication or an event bus to share the balance data between your components. Here are two solid approaches, starting with the most straightforward one for your setup:
Approach 1: Parent Component as Data Middleman (Recommended)
Since both get_data.vue and your 4 form.vue instances live under the same page/parent component, using the parent as a data hub is the cleanest, most maintainable solution. Here's how to implement it:
Step 1: Update get_data.vue to emit data to the parent
Modify your fetchBalance method to send the fetched balance data up to the parent component using Vue's $emit method:
methods: { fetchBalance() { fetch('MY-BACKEND') .then(response => response.json()) .then(data => { const freeBalance = data['freeBalance']; const totalBalance = data['totalBalance']; // Emit the data to the parent component this.$emit('balance-fetched', { freeBalance, totalBalance }); }) } }
(Pro tip: Add a mounted() hook to get_data.vue if you want to trigger the fetch automatically when the component loads.)
Step 2: Parent Component (e.g., Page.vue) hold and pass the data
In the parent component that wraps both get_data.vue and your form.vue instances:
<template> <div class="page-container"> <!-- Listen for the balance data from get_data.vue --> <get-data @balance-fetched="storeBalanceData"></get-data> <!-- Pass the shared balance data to each form instance via props --> <form-component :free-balance="freeBalance" :total-balance="totalBalance" order="amount" side="price" ></form-component> <form-component :free-balance="freeBalance" :total-balance="totalBalance" order="quantity" side="buy" ></form-component> <!-- Repeat for your remaining 2 form instances --> </div> </template> <script> import GetData from './get_data.vue'; import FormComponent from './form.vue'; export default { components: { GetData, FormComponent }, data() { return { freeBalance: null, totalBalance: null }; }, methods: { storeBalanceData(balanceData) { // Save the fetched data to the parent's state this.freeBalance = balanceData.freeBalance; this.totalBalance = balanceData.totalBalance; } } }; </script>
Step 3: Update form.vue to accept balance props
Add new props to form.vue to receive the balance data:
<template> <!-- You can now use {{ freeBalance }} and {{ totalBalance }} in your template --> <div class="form-container"> <p>Free Balance: {{ freeBalance }}</p> <p>Total Balance: {{ totalBalance }}</p> <!-- Your existing form fields here --> </div> </template> <script> export default { props: { order: { type: String, default: 'amount' }, side: { type: String, default: 'price' }, // Add new props for balance data freeBalance: { type: Number, // Adjust type to match your backend's data format (String if needed) default: 0 }, totalBalance: { type: Number, default: 0 } }, // Your existing data, methods, etc. remain unchanged data() { return { name: '', description: '', output: '' }; }, methods: { formSubmit() { let currentObj = this; axios.post('MY-BACKEND', { price: this.price, amount: this.amount, // You can use the balance props here if needed }) .then(function (response) { currentObj.output = response.data; }) .catch(function (error) { currentObj.output = error; }); } } }; </script>
Approach 2: Event Bus (For More Complex Component Relationships)
If your components aren't directly under the same parent (or you prefer a decoupled approach), you can use a Vue event bus to broadcast the balance data to all form.vue instances:
Step 1: Create an Event Bus
Make a new file (e.g., eventBus.js) to act as your global event emitter:
import Vue from 'vue'; export const EventBus = new Vue();
Step 2: Update get_data.vue to broadcast data
Import the event bus and emit the balance data when fetched:
import { EventBus } from './eventBus.js'; methods: { fetchBalance() { fetch('MY-BACKEND') .then(response => response.json()) .then(data => { const freeBalance = data['freeBalance']; const totalBalance = data['totalBalance']; // Broadcast the data to all listening components EventBus.$emit('balance-updated', { freeBalance, totalBalance }); }) } }
Step 3: Update form.vue to listen for the event
Import the event bus, listen for the balance update, and store the data locally:
import { EventBus } from './eventBus.js'; export default { data() { return { name: '', description: '', output: '', freeBalance: 0, totalBalance: 0 }; }, mounted() { // Listen for balance updates this.balanceListener = EventBus.$on('balance-updated', (balanceData) => { this.freeBalance = balanceData.freeBalance; this.totalBalance = balanceData.totalBalance; }); }, beforeDestroy() { // Clean up the listener to avoid memory leaks EventBus.$off('balance-updated', this.balanceListener); }, // Your existing props and methods remain unchanged };
Which Approach Should You Choose?
- Use the parent component middleman if your components are directly nested under the same parent—it's simpler to debug and maintain.
- Use the event bus only if your component structure is more complex (e.g., components are in different parts of the app hierarchy).
内容的提问来源于stack exchange,提问作者Jack022




