繁体   English   中英

Vue JS。 通过路由器传递道具

[英]Vue JS. Pass prop via router

我想由用户选择一个碗碟阵列,并在父组件中的selectedDishes阵列中将它们的数量放置在路由器中的所有其他组件中。 这里我有dish组件,但是我将在checkout组件中使用selectedDishes等。

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

  2. 我只想从父组件访问selectedDishes 因此,如果我更改dishcheckout组件中的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路由器中用作路径变量,您可以查询商店以获取完整的详细信息

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

Vuex文档

vuex入门

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM