如何将Laravel Blade中的Props传递至Vue.js事件总线及路由?
一、无需手动调用方法,将Props发送至Vue事件总线
你可以借助Vue组件的生命周期钩子来自动完成这件事——比如created钩子,它会在组件实例创建完成后自动触发,完全不需要手动调用方法。
步骤1:创建全局事件总线
首先在你的Vue入口文件(比如resources/js/app.js)里定义一个全局事件总线,让所有组件都能访问到:
// app.js window.Vue = require('vue'); // 创建事件总线并挂载到Vue原型上 Vue.prototype.$bus = new Vue(); // 初始化Vue实例和路由 const app = new Vue({ el: '#app', router: require('./router').default });
步骤2:在Home组件中自动发送Props到总线
修改Home组件的script部分,利用created钩子自动把props发送到总线,同时加上判断确保props存在(毕竟Blade里是登录后才传递这些值):
<script> import CoachNavbar from '../Navbars/CoachNavbar.vue' import TopNavbar from '../Navbars/TopNavbar.vue' import VideoChat from '../components/coach/VideoChatCarer.vue' import sidebar from '../Navbars/CoachNavbar.vue' export default { props: ['loggedinuser', 'pusherkey', 'pushercluster'], components: { 'coach-navbar': CoachNavbar, 'top-navbar' : TopNavbar, 'video-chat': VideoChat, 'sidebar': sidebar }, data() { return { } }, created() { // 仅当props存在时发送事件 if (this.loggedinuser && this.pusherkey && this.pushercluster) { this.$bus.$emit('home-props-ready', { loggedinuser: this.loggedinuser, pusherkey: this.pusherkey, pushercluster: this.pushercluster }); } } } </script>
之后其他组件只要通过this.$bus.$on('home-props-ready', (props) => { /* 处理接收的props */ })就能拿到这些值,全程不需要手动触发方法。
二、将Props传递给Vue Router的几种实用方式
如果事件总线的方案不符合你的需求,下面几种方式可以帮你把Blade传入的props传递给路由组件:
方式1:路由跳转时通过query参数传递
如果是从Home组件跳转到其他路由,可以在跳转时把props作为query参数携带过去:
// 可在Home组件的created钩子或其他逻辑中调用 this.$router.push({ name: 'YourTargetRoute', // 替换成你的目标路由名称 query: { loggedinuser: this.loggedinuser, pusherkey: this.pusherkey, pushercluster: this.pushercluster } });
在目标路由组件中,就可以通过this.$route.query.loggedinuser这类写法获取对应的值。
方式2:存入Vuex全局状态管理(推荐多组件共用场景)
如果这些值是多个路由组件都需要用到的,用Vuex存储会更方便:
- 先在Vuex的store中定义状态和修改方法:
// store.js export default new Vuex.Store({ state: { loggedinuser: null, pusherkey: null, pushercluster: null }, mutations: { SET_HOME_PROPS(state, props) { state.loggedinuser = props.loggedinuser; state.pusherkey = props.pusherkey; state.pushercluster = props.pushercluster; } } });
- 然后在Home组件的
created钩子中提交mutation:
created() { if (this.loggedinuser && this.pusherkey && this.pushercluster) { this.$store.commit('SET_HOME_PROPS', { loggedinuser: this.loggedinuser, pusherkey: this.pusherkey, pushercluster: this.pushercluster }); } }
之后任何路由组件都能通过this.$store.state.loggedinuser直接获取这些值,不需要在路由间手动传递。
方式3:直接从Blade注入到window对象(全局通用)
另一种更直接的方式是跳过组件props传递,把这些值直接挂载到window对象上,这样Vue Router和所有组件都能直接访问:
<!-- Blade视图文件中 --> <script> window.appSettings = { @if(auth()->check()) loggedinuser: {{ auth()->user()->id }}, pusherkey: "{{ Config::get('broadcasting.connections.pusher.key') }}", pushercluster: "{{ Config::get('broadcasting.connections.pusher.options.cluster') }}" @endif }; </script> <div id="app"> <home-component /> <!-- 现在不需要传递props了 --> </div>
之后在Vue组件或Router配置里,直接用window.appSettings.loggedinuser就能拿到对应的值,适合全局通用的配置类数据。
内容的提问来源于stack exchange,提问作者Matt B

