Vue JS。通过路由器

时间:2018-02-06 14:02:04

标签: javascript vue.js vue-router

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

  1. 如何通过路由器将selectedDishes传递给dishes组件?这样做是否正确?(我读过这个article并且它只是说:dish离开这里/dishes/:dish

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

  3. 父组件

    <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>
    

1 个答案:

答案 0 :(得分:1)

您将为菜肴创建商店,如下所示

 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 documentation

Getting started vuex