如何从外部过程更新数据?

时间:2018-10-26 14:06:24

标签: javascript vuejs2

我有一个Vue 2组件。它具有一个数据属性,我需要根据发生的外部事件进行更新。我不知道如何实现这一目标。我很高兴考虑事件或直接绑定,观察者,等等,我只是完全被互联网上使这看起来容易的各种示例所困扰,但它们都不起作用:(

我无法从顶级Vue实例向下传递道具,因为我使用的是一个提供自己组件的库,它们位于我的顶级组件和我自己的组件之间...

我正在使用Vue 2.5,并且我的组件已使用Vue.component() ...

注册

主要HTML

<div id="app">
    <f7-app :params="f7params">
        <f7-view id="main-view" main>
            <f7-page>
                <f7-navbar>
                    <div class="navbar-inner sliding">
                        <div class="header-logo-container"><img src="img/logo.png" class="logo"></div>
                        <div class="left back-btn"><a href="#" class="link icon-only invisible"><i class="material-icons">chevron_left</i></a></div>
                        <div class="right settings-btn"><a href="#" class="link icon-only"><i class="material-icons">settings</i></a></div>
                    </div>
                </f7-navbar>
                <f7-toolbar>
                    <ym-toolbar></ym-toolbar>
                </f7-toolbar>
                <ym-rootmaps></ym-rootmaps>
            </f7-page>
        </f7-view>
    </f7-app>
</div>

Vue组件注册

var rootMapsComponent = Vue.component('ym-rootmaps', {
    template: '#rootmaps',
    props: ['menuitem'],
    data: function() {
        return {
            customMenu: window.customMenuJSON,
            rootMaps: window.rootMaps,
            rootAreaImageLocation: rootAreaImageLocation
        };
    },
    created: function () {
        // `this` points to the vm instance
        console.log('Created Root Maps Component');
    }
}); 

// Init App
var vm = new Vue({
el: '#app',
data: function () {
    return {
    // Framework7 parameters here
    f7params: {
        root: '#app', // App root element
        id: 'io.framework7.testapp', // App bundle ID
        name: 'Framework7', // App name
        theme: 'md', // Automatic theme detection
        // App routes
        routes: [],
    },
    rootMaps: {},
    }
},
created: function () {
    // `this` points to the vm instance
    console.log('Created Main App');
    documentReady();
    this.$on('rootmapsUpdated', function(arg) {
        console.log('rootmapsUpdated');
        console.log(this);
        this.rootMaps = window.rootAreas;
    });
}
});

我希望能够通过外部调用此页面来按需更新rootMaps。我很高兴使用vm.$emit触发一个事件,但不知道如何获取该组件来监听它(我设法获得了顶级应用程序实例来监听该事件,但是除此之外)

有什么想法,提示,想法吗?

1 个答案:

答案 0 :(得分:0)

以下是在vuejs中使用emit的示例

在您的app.js中添加Vue.prototype.$bus = new Vue();

组件1

通过以下方式触发事件:

methods:{
    trigger() {
        this.$bus.$emit('throw-event', sample_data)
    }
}

组件2

这就是你的收听方式:

mounted () {
    this.$bus.$on('throw-event', ($data) => {
       console.log($data) // this will throw the `sample_data` in your emit
    })
}
相关问题