[英]Vue JS. Pass prop via router
我想由用户选择一个碗碟阵列,并在父组件中的selectedDishes
阵列中将它们的数量放置在路由器中的所有其他组件中。 这里我有dish
组件,但是我将在checkout
组件中使用selectedDishes
等。
如何通过路由器将selectedDishes
传递到dishes
组件? 这样做是正确的吗?(我读了这篇文章 ,它只说到:dish
从这里/dishes/:dish
离开)
我只想从父组件访问selectedDishes
。 因此,如果我更改dish
或checkout
组件中的dish
数量,则应将其发送给父组件,然后作为道具发送回子组件。 这样做对吗?
父组件 :
<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路由器中用作路径变量,您可以查询商店以获取完整的详细信息
要了解更多信息,请阅读以下网址
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.