最近学习 JavaScript, 并且使用 vuejs, 第一次使用依赖注入, 结果踩坑, 差点把屏幕摔了.. 始终获取不到如组件的属性, provide 中的 this 对象始终是子组件的 this 对象
慢慢也摸索到了些 vuejs 的一些门门道道....
错误代码 1:this 对象未定义错误
父组件
- provide:{
- getCustomerId:this
- },
子组件
inject:['getCustomerId'],
子组件调用:
- this.getCustomerId
- // 此时: getCustomerId 是未定义的
错误代码 2:this 对象未定义错误
父组件
- provide:{
- getCustomerId(){
- return this
- }
- },
子组件
inject:['getCustomerId'],
子组件调用:
- this.getCustomerId
- // 此时: 返回的 this 是子组件的 this, 此时注入的是 getCustomerId 这个方法, 而这个方法并未在组件的 methods 中声明
正确代码:
父组件
- provide(){
- return {
- getCustomerId: this.getCustomerId
- }
- },
- methods: {
- getCustomerId(){
- },
- }
子组件
inject:['getCustomerId'],
子组件调用:
- this.getCustomerId
- // 此时: 此时就对了, 注入的是父组件 methods 中定义的 getCustomerId 方法, 并且 provide() 改成的方法定义, 执行此方法时, provide 中的 this 对象也是父组件的 this 对象,
来源: http://www.bubuko.com/infodetail-3350534.html