gpt4 book ai didi

javascript - Vue.JS。通过路由器传递 prop

转载 作者:行者123 更新时间:2023-12-03 02:33:18 25 4
gpt4 key购买 nike

我希望用户在父组件中的数组 selectedDishes 中选择一组菜肴及其数量,并在路由器中的所有其他组件中使用此数据。这里我有 dish 组件,但我将在 checkout 组件等中使用 selectedDishes

  1. 如何通过路由器将selectedDishes传递给dishes组件?这样做正确吗?(我读过这篇文章 article,它只说关于让 :dish 离开这里 /dishes/:dish)

  2. 我只想从父组件访问 selectedDishes。因此,如果我更改 dishcheckout 组件中的菜肴数量,则应将其发送给父组件,然后作为 Prop 发送回子组件。这样做对吗?

父组件:

<template>
<view-router v-on:addQuantity="addQuantity(...arguments)"></view-router>
</template>
<script>
data: () => ({
//How to pass this to dishes component?
selectedDishes: [{name:'Soup', quantity: 10}, {name:'Sushi', quantity: 5}],
}),
methods: function(){
addQuantity: function(dishName){
this.selectedDishes.forEach(function(item, index){
if(item.name == dishName){
this.selectedDishes[index].quantity +=1
}
})
}
}
</script>

路由器:

import VueRouter from 'vue-router';

let routes = [
{
path: '/',
component: require ('./components/vmMain'),
children: [
{
path: 'dishes/:dish',
component: require ('./components/Dishes')
}
],
},
]

菜肴成分:

<template>
<div
// If URL is 'dishes/Soup' I want to see the following result
//<h1>Soup</h1>
//<h2>10</h2>
<h1>dish.name</h1>//currently I access it as this.$route.params.dish
<h2>dish.quantity</h2> //and don't have access to quantity
<button v-on:click="addQuantity(dish.name)">add</button>
</div>
</template>

<script>
methods: function(){
addQuantity: function(dishName){
this.$emit('addQuantity', dishName)
}
},
//How to pass prop from parent component?
props['dish']
</script>

最佳答案

您将为如下菜肴创建商店

 const store = new Vuex.Store({
state: {
dishes: [
{

name: '',
quanity: ''
}
]
},
getters: {
getAllDishes: state => state.dishes,
getDishByName: (state) => (name) => {
return state.dishes.find(dish => dish.name === name)
}
},
mutatations: {
},

})

菜肴名称可作为 vue router 的路径变量,您可以查询商店以获取完整详细信息

欲了解更多信息,请阅读以下网址

Vuex documentation

Getting started vuex

关于javascript - Vue.JS。通过路由器传递 prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48644854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com