MMTTMM
让我们使用这个组件将货币、价格和水果传递给每个组件 FruitPrices 组件:<template> <div> <!-- USD is selected by default, once the option change, the prices will be updated --> <select v-model="currency"> <!-- allows to select one currency at time, it shows all the currencies that exist in the currencies array data property --> <option v-for="(currencyOption, index) in currencies" :key="index" :value="currencyOption" > <!-- show only the currency name as option --> {{ currencyOption.name }} </option> </select> <div v-for="(fruit, fruitIndex) in fruitsWithPrices" :key="fruitIndex"> <!-- if everything is working fine, you don't need close tags for empty custom component, you can use '/' at the end of the first tag to self close it--> <FruitPrices :name="fruit.name" :convertedPrice="fruit.convertedPrice" /> </div> </div></template><script>import FruitPrices from '../somePlace/FruitPrices'export default { name: "FruitPricesContainer", components: { FruitPrices }, data: () => ({ fruits: [ { name: 'Apple', price: 0.2 }, { name: 'Banana', price: 0.3 }, { name: 'Orange', price: 0.25 } ], currency: { // Base currency, exchangeRate = 1 exchangeRate: 1, name: 'USD' }, // Used exchange rates only for demo purpose, not are the real and valid exchange rates currencies: [ { exchangeRate: 1, name: 'USD' }, { exchangeRate: 1.2, name: 'EUR' }, { exchangeRate: 0.7, name: 'SGD' }, { exchangeRate: 700, name: 'MXN' }, { exchangeRate: 3700, name: 'COP' } ] }), computed: { // The fruitsWithPrices listen for changes in both, the fruit and // the currency, so once you change it by selecting a different currency // the prices will be updated automatically (nice) fruitsWithPrices() { return this.fruits.map((fruit) => { return { ...fruit, // Add name and original price to the returned object convertedPrice: fruit.price * this.currency.exchangeRate // Add the price based on the exchange rate } }) } }}</script>现在,让我们创建 FruitPrices 组件:<template> <div> <p>{{ name }}: {{ convertedPrice }}</p> </div></template><script>export default { name: "FruitPrices", props: { name: { type: String, required: true }, convertedPrice: { type: Number, required: true } }}</script>它已经准备好了!(Tbh,我没有测试它,如果您有错误或问题,请告诉我)。