Event_Bus vue变量访问单文件组件Vue.js - Laravel混合

Event_Bus vue variable access to single file component Vue.js - Laravel Mix

我只想问一下vue的单文件组件如何访问一个变量? 当我尝试在浏览器上访问我的应用程序时,vue js 会导致错误。

Error in mounted hook: "ReferenceError: EventBus is not defined"

下面是我的代码。

我在 app.js

上实现了这个
window.Vue = require('vue');
var EventBus = new Vue();

    Vue.component('transactionslist', require('./components/TransactionList.vue'));

    const app = new Vue({
        el: '#transaction',
        methods: {
            getTransactions: function () {
                $.getJSON("/guard/station/transactions?search=" + this.Search, function (_transactions) {
                    this.Transactions = JSON.parse(JSON.stringify(_transactions));
                }.bind(this));
            }
        },
        data() {
            return {
                Search: '',
                Transactions: [],
            }
        },
        mounted: function () {
            this.getTransactions();

        }
    });

这是我的 vue 组件 (TransactionList.vue)

<template>
    <table class="table table-hover transaction-list">
        <thead>
            <tr>
                <th class="fit">Transfer Code</th>
                <th>Orgin</th>
                <th>Destination</th>
                <th class="fit">Date Created</th>
            </tr>
        </thead>
        <tbody>
            <transactionRow @rowSelected="isSelectedRow" v-for="trans in data" :origin="trans.Origin" :destination="trans.Destination"
                :date="trans.created_at" :key="trans.TransferCode" :tscode="trans.TransferCode">
            </transactionRow>
        </tbody>
    </table>
</template>

<script>
    export default {
        props: ['data'],
        created() {
            this.transactions = this.$children;
        },
        data() {
            return {
                transactions: [],
                Transaction: []
            }
        },
        methods: {
            isSelectedRow: function (payload) {
                EventBus.$emit('showSelected', payload);
                this.transactions.forEach(transaction => {
                    transaction.isActive = (transaction.tscode == payload.tscode);
                });
            },
        }

    }
</script>

我使用 laravel 开发应用程序并使用 laravel 功能之一,即 laravel Mix。

就用这个:

window.EventBus = new Vue();

在它自己的文件中创建事件总线:

// bus.js
import Vue from 'vue'
const bus = new Vue()
export default bus

将其导入到您要使用它的组件中:

import bus from 'bus'
export default { 
   ...
   methods: {
       myMethod () {
           bus.$emit('my-event', 'test')
       }
    }
   ...
}

您刚刚在 app.js 文件中定义了 EventBus

它在 TransactionList.vue 组件中不可访问,因为它没有引用 EventBus

因此将 app.js 中的 EventBus 导出为

export const EventBus = new Vue();

然后将组件脚本中的 EventBus 导入为

<script>
    import {EventBus} from './path/to/app.js'
    export default {

    }
</script>

参见 es6 import and export