请看是否有人已经问过类似的问题,你已经可以找到两个类似的问题:
Vue.js, pass data to component on another route
Passing props to Vue.js components instantiated by Vue-router
无论如何,一种解决方案是将您的数据作为参数传递给router.push 方法。
如果您还想在其他组件中使用 menuItemsData,您应该考虑的另一个解决方案是使用 vuex 进行状态管理。
1.使用router.push 参数字段:
您可以通过router.push 将 menuItemsData 作为参数传递:
router.push({
path: '/',
params: {
menuItemsData: menuItemsData
}
});
然后你可以在你链接到你的根 url 的组件中接收数据:
export default {
name: 'timeselect',
props: ['menuItemsData'],
};
在注册 timeselect 路由时不要忘记添加props: true 选项。
new Router ({
routes: [
path: '/',
component: timeselect,
props: true
]
})
2。使用 vuex store 进行全局状态管理:
对于这个概念的正确实现,vuex 有一个非常好的文档,带有示例代码 sn-ps。
包含您的数据的简单存储可能如下所示:
// Here we create the state where our data is stored
const state = {
totalBill: 0.0,
menuItemsData: {
Glazed: {
name: 'Chocolate',
qty: 0,
price: 2.00
},
Chocolate: {
name: 'Glazed',
qty: 0,
price: 2.00
}
}
}
// Here we define the getters to access our data
const getters = {
getMenuItemsData: state => state.menuItemsData,
getTotalBill: state => state.totalBill
}
// Here we define mutations which are used for changing our state data
const mutations = {
addToTotalBill: (state,amount) => state.totalBill += amount
}
// Then we create a new vuex store instance containing our data and the getter, ther you would also add the Mutations for updating the data
const store = new Vuex.Store({
state,
getters,
mutations
})
// Our Vue component which maps our getters to access our data from the vuex store
new Vue({
store,
el: '#container',
computed: Vuex.mapGetters(['getMenuItemsData', 'getTotalBill']),
methods: Vuex.mapMutations(['addToTotalBill'])
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="container">
<ul>
<!-- Now we can just access our data from the store in the component -->
<h3> Menu Items from store: </h3>
<li v-for="item in getMenuItemsData">
<span>{{ item.name }} - </span>
<span @click="addToTotalBill(item.price)" style="text-decoration: underline; cursor: pointer;">add to Bill</span>
</li>
<br>
<span>Total Bill:</span>
{{ getTotalBill }}
</ul>
</div>