【发布时间】:2020-02-22 11:02:27
【问题描述】:
vue 路由有问题。我正在使用带有 vue@2.6.10 的 laravel 6
我想在标题中动态创建动作按钮(动作不同,取决于组件)。这个 AppHeader 组件在每个组件上,并且在我想在标题中创建当前组件的事件的当前组件上。
例如组件CategoryDetails我想在头部有两个动作(保存和退出)。
该类别的路线是这样的:
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
}
},
]
在组件CategoryDetails中:
<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