简体   繁体   中英

VueJS - Communicating from child component to parent not working

I'm in the beginning stages of learning VueJS and am building a quick and dirty 'todo' list to get a hold of the basics.

For some reason I'm having trouble raising an event in a child component and then having the parent component respond to that event, I've followed the documentation for emitting an event in the child and then binding to it in the parent with:

v-on:my-event=""

Etc... but the event is never run on the parent component.

Example child component:

var todoHeader = {
    template: `<nav><button v-on:click="switchView('list')">View List</button><button v-on:click="switchView('add')">Add Todo</button></nav>`,
    methods: {
        switchView: function(view) {
            this.$emit('switch-view', view)
        }
    }
};

Example parent which listens to the switch-view event being raised:

Vue.component('todo-list', {
   data: function() {
   return {
       currentView: ''
   }
},
components: {
  'todo-header': todoHeader,
  'list-todos': listTodos,
  'add-todo': addTodo
},
template: 
   `<div v-on:switch-view="onSwitchView"><todo-header></todo-header>
   <list-todos></list-todos>
   <add-todo></add-todo></div>`,
methods: {
   onSwitchView: function(view) {
       console.log(view);
   }
}
});

I should be seeing the selected view being logged to the console but I get nothing, can anyone see what I've done wrong? My intention is to have a navigation bar with two buttons for controlling the current view, either list or add mode. The child add/list components would listen to this value and toggle accordingly.

Here's a JSFiddle

You should put the event listeners on the child component's custom tag:

template: 
   `<div>
        <todo-header v-on:switch-view="onSwitchView"></todo-header>
        <list-todos></list-todos>
        <add-todo></add-todo>
    </div>`,

Fixed jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM