Vue父组件调用子组件方法,报错[Vue warn]: Error in v-on handler: “TypeError: _this.$emit is not a function“

症状

一开始浏览器控制台报这个错[Vue warn]: Error in v-on handler: "TypeError: _this.$emit is not a function",明显就是this指向问题,名为ajax的方法在父组件中,而this是子组件。

<!-- 子组件 -->
<template><el-pagination
          layout="prev, pager, next"
          :page-count="pageCount"
          :current-page="index"
          @current-change="handlePageChange"
          hide-on-single-page
        >
        </el-pagination></template>

<script>
export default {
      
      
  data () {
      
      
    return {
      
      }
  },
  props: {
      
      },
  methods: {
      
      
    handlePageChange: (page) => {
      
       // 箭头声明
      this.$emit('pageChange', page) // emit对父组件可见
    }
  }
}
</script>

<style scoped></style>
<!-- 父组件 -->
<template>
  <el-container class="container-admin">
     <my-table
       ref="table"
       :index="index"
       :pageCount="pageCount"
       :editable="editable"
       :heads="heads"
       :data="data"
       @pageChange="handlePageChange"
     />
  </el-container>
</template>

<script>
import MyTable from '@/components/MyTable.vue'
importexport default {
      
      
  components: {
      
       MyTable },
  data () {
      
      
    return {
      
      
      tableName: '/lib/list',
      index: 1,
      size: 3,
    }
  },
  mounted () {
      
      
    this.ajax(this.tableName, this.index, this.size)
  },
  methods: {
      
      
    ajax (url, index, pageSize) {
      
       // ajax方法},

    handlePageChange: (index) => {
      
      
      this.index = index
      this.ajax(this.tableName, this.index, this.size) //在这里调用
    },
  }
}
</script>

<style scoped></style>

然后我改了一下,把子组件中的声明换成了function

// 子组件
methods: {
    
    
  handlePageChange: function (page) {
    
     // 改
    this.$emit('pageChange', page) // emit对父组件可见
  }
}

然后错误变了:[Vue warn]: Error in v-on handler: "TypeError: _this2.ajax is not a function"。可以发现,子组件中的function声明让this.$emit中的this指针指向子组件,那么…

解决办法

把两个方法都改成function声明,不要箭头声明。
代码现已正常工作。

猜你喜欢

转载自blog.csdn.net/dscn15848078969/article/details/120565622