症状
一开始浏览器控制台报这个错[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'
import …
export 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声明,不要箭头声明。
代码现已正常工作。