Javascript 如何访问Vue中所有组件中对象内部的数据

Javascript 如何访问Vue中所有组件中对象内部的数据,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,我是Vue的新手,被这件事缠住了。我想访问存储在我的一个组件中的对象中的数据。我试图制作一个用于练习的购物车系统,并为一些游戏硬编码数据,以便在应用程序中访问它。我的对象代码如下 products: [ { id: 1, name: 'Call of Duty: Modern Warfare', price: 'Rs. 5,500',

我是Vue的新手,被这件事缠住了。我想访问存储在我的一个组件中的对象中的数据。我试图制作一个用于练习的购物车系统,并为一些游戏硬编码数据,以便在应用程序中访问它。我的对象代码如下

products: [
                { 
                    id: 1, 
                    name: 'Call of Duty: Modern Warfare',
                    price: 'Rs. 5,500',
                    shortDesc: 'Call of Duty: MW returns. This game is a complete revamp of the old COD:MW',
                    description: 'Call of Duty: MW returns. This game is a complete revamp of the old COD:MW',
                    inStock: 'yes',
                    availableQuantity: '100',
                    img: 'src/assets/img/codmw.jpg',
                },
                { 
                    id: 2, 
                    name: 'PlayerUnknowns Battlegrounds',
                    price: 'Rs. 600',
                    shortDesc: 'Call of Duty: MW returns. This game is a complete revamp of the old COD:MW',
                    description: 'Call of Duty: MW returns. This game is a complete revamp of the old COD:MW',
                    inStock: 'yes',
                    availableQuantity: '500',
                    img: 'src/assets/img/pubg.jpg',
                },
                { 
                    id: 3, 
                    name: 'GTA VI',
                    price: 'Rs. 10,000',
                    shortDesc: 'Call of Duty: MW returns. This game is a complete revamp of the old COD:MW',
                    description: 'Call of Duty: MW returns. This game is a complete revamp of the old COD:MW',
                    inStock: 'yes',
                    availableQuantity: '5',
                    img: 'src/assets/img/gta.jpg',
                }
            ]
上述数据保留在Shop.vue组件中,每当用户单击“查看产品”按钮时,就会调用该特定产品的单独路线,我希望在该路线中获取特定游戏的数据。为此,我在Shop.vue中制作了一个按钮,如下所示

<router-link 
    class="btn btn-primary" 
    :to="/view/ + game.id" 
    v-b-tooltip.hover title="View Product details">
    View Product
</router-link>
但现在我需要知道如何访问数据,其中产品ID是ViewProduct.vue组件中的动态ID,因为产品对象位于Shop.vue组件中


请帮我解决这个问题,你最好使用一个全局状态

最简单的方法是使用


您可以将您的
产品设置为状态,并添加一个getter,用于根据id获取产品。

Vuex将为您解决此问题。您还可以在组件之间传递道具,如下所示:

const router = new VueRouter({
  routes: [
    { path: '/view/ + game.id', component: ViewProduct.vue, props: { id:this.id } }
  ]
})
在ViewProduct组件中:

export default {
        data() {
            return {

                },
            };
        },
        props: ['id'],     <===== *props*
        computed: {

        },
        methods: {
        },
this.$props.id

如果要在组件之间共享数据,请使用
vuex
,这样您就可以随时随地访问
this.$props.id