简体   繁体   English

VueJS-从子组件到父组件的通信不起作用

[英]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. 我正处于学习VueJS的初期阶段,正在构建一个快速且肮脏的“待办事项”列表,以掌握基本知识。

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: 侦听正在引发的switch-view事件的示例parent:

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 这是一个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 固定jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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