我正在使用Vue.js模板。我想将menuItemsData传递给另一个vue组件(timeselect)(在图2中我推送到另一个组件timeselect)。我看过多个教程,但我不知道如何在这里使用v-bind
?
即使我设法把它推到另一个组件,我怎么才能收到它?
答案 0 :(得分:0)
如果有人问过类似的问题,请查看两个类似的问题:
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
params字段:
您可以通过router.push
传递menuItemsData作为参数:
router.push({
path: '/',
params: {
menuItemsData: menuItemsData
}
});
然后,您可以在链接到根网址的组件中接收数据:
export default {
name: 'timeselect',
props: ['menuItemsData'],
};
注册timeselect路线时,请不要忘记添加props: true
选项。
new Router ({
routes: [
path: '/',
component: timeselect,
props: true
]
})
<强> 2。使用vuex store进行全局状态管理:
为了正确实现这个概念,vuex提供了一个包含示例代码片段的非常好的文档。
包含数据的简单商店可能如下所示:
// 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>