代码之家  ›  专栏  ›  技术社区  ›  Archeg

使用Vue中的总线模式从一个组件更改另一个组件的状态。js 2

  •  0
  • Archeg  · 技术社区  · 8 年前

    我的主组件有一个加载程序,如果有东西加载到任何子组件上,它会阻止视图。我希望能够从子组件向父组件发送命令“load is finished”。

    主要部件有:

     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>
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Sergio Baidon    8 年前

    所以问题是你在宣布 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>