我正在 Vue 3 中創建一個簡單的購物車用于學習目的。
到目前為止,我已經設定了從products物件到addToCart()功能的所有內容,并且所有內容都在一個v-for回圈中運行。
問題是我需要在位于回圈之外的警報中顯示產品的標題v-for,我不知道如何在 Vue 中做到這一點。
我試過了emit,provide但它不起作用。Alert.vue我可以通過將整個物件發送到子組件,provide但這沒有幫助,因為我只需要獲取所選產品的當前索引即可獲取其標題。
你可以在這里查看演示https://codesandbox.io/s/vue-cart-54ioqt?file=/src/App.vue
嘗試將產品添加到購物車兩次并檢查警報。目前它正在顯示整個購物車物件,但我只需要獲取title產品的,這樣警報就會說You have already added {product.title} to your cart
應用程式.vue
export default {
name: 'App',
components: {
CartAlert
},
data() {
return {
products: [
{id: 1, title: 'Samsung A70', price: 50},
{id: 2, title: 'Kindle Reader', price: 50},
{id: 3, title: 'Meta Quest 2', price: 100},
{id: 4, title: 'LG LED 43" TV', price: 200},
],
discountInput: '',
discountValid: false,
cart: [],
total: '',
alreadyAddedToCart: false
}
},
methods: {
addToCart(index) {
if (this.cart.includes(this.products[index])) {
this.alreadyAddedToCart = true
} else {
this.cart.push(this.products[index])
}
},
},
provide() {
return {
cart: this.cart
}
}
}
Alert.vue(子組件)
<template>
<div id="alert" class="alert alert-danger alert-dismissible fade show" role="alert">
You have already added this {{ cart }} to your cart.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"
@click="$emit('dismissAlert')"></button>
</div>
</template>
<script>
export default {
name: "CartAlert",
props: ['product'],
inject: ['cart'],
mounted() {
console.log()
}
}
</script>
uj5u.com熱心網友回復:
product您可以在 Cart 組件中顯示您的道具:
You have already added this {{ product }} to your cart.
在應用程式中添加item資料功能:
item: null
在方法中為該資料屬性添加標題:
this.item = this.products[index].title
this.alreadyAddedToCart = true;
在模板中將您的屬性系結到item:
:product="item"
你的演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/475754.html
標籤:javascript Vue.js Vue组件 Vuejs3
上一篇:如何將react-phone-input-2與Typescript一起使用
下一篇:洗掉表行按鈕洗掉所有后續行
