【问题标题】:create dynamic events for a vue component为 Vue 组件创建动态事件
【发布时间】:2020-02-22 11:02:27
【问题描述】:

vue 路由有问题。我正在使用带有 vue@2.6.10 的 laravel 6

我想在标题中动态创建动作按钮(动作不同,取决于组件)。这个 AppHeader 组件在每个组件上,并且在我想在标题中创建当前组件的事件的当前组件上。

例如组件CategoryDe​​tails我想在头部有两个动作(保存和退出)。

该类别的路线是这样的:

        path: '/',
        redirect: 'dashboard',
        component: DashboardLayout,
        children: [
            {
                path: '/categories',
                component: Category,
                name: 'category',
                meta: {
                    requiresAuth: true
                }
            },
            {
                path: '/categories/:CategoryID',
                component: CategoryDetails,
                name: 'category-details',
                props: true,
                meta: {
                    requiresAuth: true
                }
            },
        ]

在组件CategoryDe​​tails中:

<template>
    <div>
        <app-header :actions="actions"></app-header> 
        // other code
    </div>
</template>

<script>
    import AppHeader from "../../layout/AppHeader";
    export default {
        name: "CategoryDetails",
        components: {AppHeader},
        data() {
            actions: [{label: 'Save', event: 'category.save'}, {label: 'Exit', event: 'category.exit'}],
        },
        mounted() {
            const vm = this;
            Event.$on('category.save', function(){
                alert('Save Category!');
            });
            Event.$on('category.exit', function(){
                vm.$router.push({name: 'category'});
            });
        }
    }
</script>

我创建了 action 对象,它告诉头部组件要发出什么事件并在这个组件中监听它们。

在 AppHeader 组件中:

<template>
    <div v-if="typeof(actions) !== 'undefined'" class="col-lg-6 col-sm-5 text-right">
        <a href="javascript:void(0)" class="btn btn-sm btn-neutral" v-for="btn in actions" @click="onActionClick(btn.event)">{{ btn.label }}</a>
    </div>
</template>
<script>
export default {
    name: "AppHeader",    
    props: [
        'actions'
    ],
    methods: {
        onActionClick(event) {
            Event.$emit(event);
        }
    }
}
</script>

Event 是 app.js 中定义的“总线事件”

/**
 * Global Event Listener
 */

window.Event = new Vue();

所以...让我们测试一下:)

我在类别组件中。单击类别详细信息...操作在标题中(保存并退出)。单击退出...我们将区域推回类别组件...再次单击以进入类别详细信息并单击保存...警报出现两次。

退出并再次输入...警报“保存类别!”出现 3 次……以此类推……

为什么?

【问题讨论】:

    标签: laravel vue.js vue-router


    【解决方案1】:

    我认为问题不在于您的路线。我不知道,但请尝试在感兴趣的组件中本地(而不是全球)测试您的事件。可能存在重复操作(CategoryDe​​tails)。

    【讨论】:

      【解决方案2】:

      据此贴:https://forum.vuejs.org/t/component-not-destroying/25008/10

      我必须破坏“僵尸效应”

      destroyed() {
          Event.$off('category.save');
          Event.$off('category.exit');
      }
      

      【讨论】:

        猜你喜欢
        • 2020-02-29
        • 1970-01-01
        • 2017-04-13
        • 2019-07-12
        • 2019-03-31
        • 2021-12-27
        • 1970-01-01
        • 2019-10-15
        • 1970-01-01
        相关资源
        最近更新 更多