Vue 2.0:父母没有回应儿童事件

时间:2017-06-27 13:39:44

标签: javascript vue.js vuejs2 vue-component

我有一个带有按钮的侧边栏子组件可以更改标签:

<script type="text/x-template" id="employee-sidebar">
    <div class="sidebar full-height col-" data-color="purple">
        <div class="sidebar-wrapper" id="dash-board">
            <ul class="nav">
                <li v-bind:class="{ active: activeLink == 'dashboard' }">
                    <a href="#dashboard" @click="changeTab('dashboard')">
                        <i class="material-icons">dashboard</i>
                        <p>Dashboard</p>
                    </a>
                </li>
                <li v-bind:class="{ active: activeLink == 'team' }">
                    <a href="#radio" @click="changeTab('team')">
                        <i class="fa fa-users"></i>
                        <p>Team</p>
                    </a>
                </li>
                <li class="text-center"><button class="btn btn-primary clear-filter">Clear</button></li>
            </ul>
        </div>
    </div>
</script>

当我致电@click="changeTab('dashboard')"时,它会调用子组件中的某个函数并发出changeTab事件:

Vue.component('employee-sidebar', {
  template: '#employee-sidebar',
  props: {},
  data: function() {
    return {
      activeLink: 'dashboard'
    }
  },
  methods: {
    changeTab: function(tab) {
      // Always see this console log
      console.log(tab)
      this.activeLink = tab
      this.$emit('changeTab', tab)
    }
  }
})

当我在父母中调用组件时,我会监听此事件:

<employee-sidebar v-on:changeTab="changeTheTab(activeLink)"></employee-sidebar>

但是永远不会在父级中调用changeTheTab()函数:

changeTheTab: function(tab) {
  // Never see this console log
  console.log(tab)
  this.activeLink = tab
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

感谢@wostex的小写提示,我能够将我的组件更新为以下内容:

Vue.component('employee-sidebar', {
  template: '#employee-sidebar',
  props: {},
  data: function() {
    return {
      activeLink: 'dashboard'
    }
  },
  methods: {
    changeTab: function(tab) {
      console.log(tab)
      this.activeLink = tab
      this.$emit('change_tab', tab)
    }
  }
})

并在父母:

<employee-sidebar v-on:change_tab="(tab) => activeLink = tab"></employee-sidebar>