首页 > 解决方案 > 如何在 Vue.js 上的组件之间传递事件信息

问题描述

我的任务是使用 Vue.js 构建一个在线食品订购系统。

正如您在我的JsFiddle上看到的,我在页面顶部显示了一个菜单部分列表。

我要做的是:单击菜单部分时,我想做一个ajax请求并获取完整的部分信息并将其传递给menu-section-info组件。

然后我还希望能够知道用户是否单击了添加到收藏夹并将其传递给ajax请求。

我知道如何发出ajax请求,但我不熟悉事件vue.js以及如何使用这些在组件之间传递信息。

看起来我可以将 'v-on:click' 属性添加到菜单部分组件或其中的 li 项。这会是正确的方法吗?以及如何将单击的菜单部分详细信息传递给菜单部分信息组件?

提前致谢

Vue.component('menu-section', {
    props: ['menusection'],
    template: '<li>{{ menusection.name }}</li>'
})

Vue.component('menu-section-info', {
    props: ['menusectioninfo'],
    template: '#menusectioninfo-template'
})

new Vue({
        el:'#app',
    data: {
            // this will be retrieved using an ajax request
        menuSectionList: [
            { id: 1, name: 'Pizzas' },
            { id: 2, name: 'Burgers' },
            { id: 3, name: 'Wraps' },
            { id: 4, name: 'Drinks' },
            { id: 5, name: 'Sweets' }
        ]
    }
})

<script src="https://unpkg.com/vue"></script>

<div id="app">
        <ol>
            <menu-section v-for="item in menuSectionList"
                        v-bind:menusection="item"
                        v-bind:key="item.id">
            </menu-section>
        </ol>

        <div style="margin-top:20px;">
         <!-- The info here has been hardcoded, it should be retrieved using an ajax request when one of the sections has been clicked. The favourites link should also make and ajax request passing the selected section. -->
          <menu-section-info menusectioninfo="We sell the best burgers in the world!"></menu-section-info>
        </div>
</div>

<script type="text/x-template" id="menusectioninfo-template">
  <div>
    <div>{{ menusectioninfo }}</div>
    <div><a href="#">Click here to add section to your favourites list</a></div>
  </div>
</script>

标签: javascriptvue.jsvuejs2vue-component

解决方案


推荐阅读