【问题标题】:VueJS events between two separate components两个独立组件之间的 VueJS 事件
【发布时间】:2018-01-15 09:35:22
【问题描述】:

我在 Laravel 5.5 中使用 VueJS。我在同一页面中使用了两个组件。其中一个创建项目,另一个按顺序列出项目。所以我想要实现的是当Item创建成功时,ItemList组件应该更新自己并通过发出AJAX请求来获取最新的项目。

在ItemCreate组件ItemCreate.vue:

methods: {
        sendItemData: function () {
            this.$emit('items-updated');
            axios.post('/dashboard/item', {
                name: this.itemName,
            })
                .then(function (response) {
                    if (response.status === 201) {
                        toastr.success('Crawler created successfully!', {timeout: 2000});
                        this.$emit('items-updated');
                    }
                })
                .catch(function (error) {
                    toastr.error(error, 'Ooops! Something went wrong!');
                })
        }

在ItemList组件上ItemList.vue

methods: {
        getItems: function () {
            axios.get('/items')
                .then(function (response) {
                    this.items = response.data;
                })
                .catch(function (error) {
                    toastr.error(error, 'Ooops! Something went wrong!');
                })
        },
    },
    mounted() {
        this.$on('items-updated', function () {
            this.getItems();
        })
    }

最后这里是主要的app.js 设置:

require('./bootstrap');

window.Vue = require('vue');

Vue.component('item-list', 
  require('./components/entities/item/ItemList'));
Vue.component('item-create', 
  require('./components/entities/item/ItemCreate'));

const app = new Vue({
    el: '#app'
});

【问题讨论】:

    标签: laravel-5 vue.js vuejs2


    【解决方案1】:

    您需要使用global EventBus:

    在 main.js 中:

    window.EventBus = new Vue();
    

    然后在你的组件中:

    EventBus.$emit('items-updated');
    
    EventBus.$on('items-updated',() => {});
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2018-02-08
    • 1970-01-01
    • 2020-10-16
    • 2018-05-22
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 2012-07-21
    相关资源
    最近更新 更多