父组件
<template>
<div>
<el-row>
<Tree/>
</el-row>
<el-row>
<Tree :handleNodeClick="handleNodeClick" />
</el-row>
</div>
<script>
import Tree from './Tree'
export default {
components: {
Tree
},
methods: {
handleNodeClick(data) {
console.log('父组件', data, 'this', this);
}
},
}
</script>
子组件
<template>
<div >
<el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
</div>
</template>
<script>
export default {
props: {
handleNodeClick: {
type: Function,
default (data) {
// this为空
console.log('子组件', data, 'this', this)
}
}
}
}
</script>
上面的代码 在父组件不传handleNodeClick时,想要子组件使用default函数,但是访问不到this 要怎么办?
发现有些场景下this是本组件实例,有些场景下this为null,调试后发现不行的场景是vue主动绑定this 为 null,下面是 vue2.6.11 版本构建的 vue.esm.js
解决方法是在子组件中手动bind一次