【问题标题】:how to pass data to another vue.js component如何将数据传递给另一个 vue.js 组件
【发布时间】:2018-08-12 11:24:11
【问题描述】:

我正在使用 Vue.js 模板。我想将 menuItemsData 传递给另一个 vue 组件(timeselect)(在图 2 中,我推送到另一个组件 timeselect)。我查看了多个教程,但不知道如何在此处使用 v-bind

即使我设法将它推送到其他组件,我将如何接收它?

【问题讨论】:

  • 将您的代码分享为文本而不是图片。

标签: vue.js vuejs2 vue-component vue-router


【解决方案1】:

请看是否有人已经问过类似的问题,你已经可以找到两个类似的问题:

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>

【讨论】:

    猜你喜欢
    • 2018-07-19
    • 2018-04-17
    • 1970-01-01
    • 2020-10-11
    • 2023-03-04
    • 2020-06-21
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多