vue的方法中不要用箭头函数,因为箭头函数会绑定父作用域上下文,指向的就不是我们所期望的vue实例
import iButton from './components/button'
export default {
components: {
iButton
},
methods: {
//错误
clickBtn: () => {
console.log(this) // 指向当前页面模块对象
this.$refs.btn.sayHello() // TypeError: Cannot read property 'btn' of undefined
},
// 正确
clickBtn () {
console.log(this)
this.$refs.btn.sayHello() // 能正常访问组件中方法
}
}
}