Vuejs从组件向主vue实例发出单击

时间:2018-05-28 12:31:48

标签: javascript vue.js

我正在尝试从我的组件向我的主vue实例发出一个click事件,但我能够解决它。目前我的控制台没有收到任何消息,所以它没有事件转到该功能所以代码到目前为止看起来像这样:

// component LeftUserListTileComponent
<template>
    <v-list-tile @click="$emit('toggleLeftUserPanel')">
        <v-list-tile-action>
            <v-icon>exit_to_app</v-icon>
        </v-list-tile-action>
        <v-list-tile-content>
            <v-list-tile-title>User Settings</v-list-tile-title>
        </v-list-tile-content>
    </v-list-tile>
</template>

<script>
    export default {
        data () {
            return {
            }
        },
        methods:{
            toggleLeftUserPanel () {
                // what to do here?
            }
    };
</script>

Vue.component('left-user-list-tile', require('./components/LeftUserListTileComponent.vue'));
Vue.component('left-user-panel', require('./components/LeftUserPanelComponent.vue'));

const app = new Vue({
    el: '#app',

    props: {
      source: String
    },

    data: {
        leftUserPanel: null
    },

    toggleLeftUserPanel () {
        console.log("In toggleLeftUserPanel func");
        this.leftUserPanel != this.leftUserPanel;
    }


});

2 个答案:

答案 0 :(得分:0)

如果您在点击时直接发出事件,则在第一个toggleLeftUserPanel ()中您不应再执行任何操作。

为了工作,你应该从它的孩子那里收到 toggleLeftUserPanel parent时声明你对event元素的期望,例如:

<toggle-left-user-panel @toggleLeftUserPanel='togglePanel' />

然后在父methods中定义此方法:

methods(){
    togglePanel() {
         //your action here
    }
}

通过这种方式,启用了父子通信,父母应该对子emit事件做出反应。

希望它有所帮助!

答案 1 :(得分:0)

如果要发出事件,则需要在组件内设置此事件。如果您只想在用户点击标题时获取点击,您应该可以使用@ click.native:

<v-list-tile @click.native="console.log('Title is clicked!')">
...
相关问题