vue.js - 在另一个 Vue 组件中访问 Vuex 存储状态数组详细信息
问题描述
我有一个市场,我将从本地存储中选择的产品存储在cart
其中,Vuex Store
以便JSON
与其他组件共享它们。现在,当客户购买产品时,我想访问cart
详细信息并将其与他们的姓名和其他信息一起存储在数据库中,但我无法访问JSON
我想要的详细信息Vuex Store
。
Vuex:
let cart = window.localStorage.getItem('cart')
const store = createStore({
state: {
cart: cart ? JSON.parse(cart) : [],
},
})
结帐 Vue 组件:.map()
我得到另一个数组,我想得到一个值。我也尝试过.forEach()
,但我得到了未定义的值。
export default {
data() {
return {
customers: {
name:'',
adress:'',
town:'',
email:'',
phone:'',
title : this.$store.state.cart.map(function (detail){
return detail.ropeTitle
}),
diameter: this.$store.state.cart.map(function (detail) {
return detail.ropeDiameter
}),
price: this.$store.state.cart.map(function (detail) {
return detail.ropePrice
}),
cartQuantity: this.$store.state.cart.map(function (detail) {
return detail.ropeQuantity
})
},
}
},
methods: {
async handleSubmitForm() {
try {
await axios.post('http://localhost:3000/api/orders/customers', this.customers)
.then(() => {
this.$router.push('/customers')
this.customers = {
name:'',
adress:'',
town:'',
email:'',
phone:'',
title : '',
diameter: '',
price: '',
cartQuantity: '',
}
router.go(-1)
})
} catch (error) {
console.log(error)
console.log(this.customers)
}
}
}
}
你能帮忙吗?
解决方案
所以我在吸气剂中将细节作为单独的状态,如下所示:
setTitle: state =>{
let oneItem=''
state.cart.forEach((item)=>{
oneItem=item.ropeTitle
})
return oneItem
},
然后我在这样的组件中使用它:
title : this.$store.getters.setTitle,