【问题标题】:Change state of one component from another using bus pattern in Vue.js 2使用 Vue.js 2 中的总线模式从另一个组件更改一个组件的状态
【发布时间】:2018-01-25 14:25:53
【问题描述】:

我的主组件有一个加载器,如果在任何子组件上加载某些内容,它会阻止视图。我希望能够从子组件向父组件发送命令“加载完成”。

主要组件有:

 data: function() {
            return {
                isLoading : false
            }
        }

这应该改变。

我尝试使用文档中指定的总线模式 (https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication)

我在根目录中创建了event-bus.js,内容为export const EventBus = new Vue();

现在在主组件中,我想订阅事件并更改状态,但是如果我写:

 var eventBus = require("./event-bus.js").EventBus;
    eventBus.$on('isLoadingChanged', receivedLoading => {
        isLoading = receivedLoading;
    });

我收到isLoading is not defined。如何更改状态?

请注意,我使用的是vue 文件。我的整个主要组件如下所示:

<template>
    <div>
        <div class="globalLoader" v-if="isLoading">
            <GridLoader></GridLoader>
            <!--<p>Loading...</p>-->
        </div>
        <content-component></content-component>
    </div>
</template>

<script>

    var GridLoader= require('vue-spinner/dist/vue-spinner.min').GridLoader;

    var eventBus = require("./event-bus.js").EventBus;
    eventBus.$on('isLoadingChanged', receivedLoading => {
        isLoading = receivedLoading;
    });

    var d = {
        components: {
            'content-component': ...,
            'GridLoader': GridLoader
        },

        data: function() {
            return {
                isLoading : false
            }
        }
    };

    export default d;
</script>

【问题讨论】:

    标签: javascript vuejs2


    【解决方案1】:

    所以问题是您在组件的数据中声明 isLoading 属性

    为了能够访问该属性,您需要使用this.isLoading

    我建议在组件的生命周期方法之一中声明对事件的处理。

    代码应如下所示:

    .... 
    <script>
    
    var GridLoader= require('vue-spinner/dist/vue-spinner.min').GridLoader;
    
    var eventBus = require("./event-bus.js").EventBus;
    
    var d = {
        components: {
            'content-component': ...,
            'GridLoader': GridLoader
        },
    
        data: function() {
            return {
                isLoading : false
            }
        },
        created: function() {
          eventBus.$on('isLoadingChanged', receivedLoading => {
            this.isLoading = receivedLoading;
          });
        }
    };
    
    export default d;
    </script>
    

    【讨论】:

      猜你喜欢
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      • 2020-06-05
      • 2016-07-14
      • 2017-06-12
      相关资源
      最近更新 更多