zoukankan      html  css  js  c++  java
  • Vue.js provide / inject 踩坑

    最近学习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对象,

  • 相关阅读:
    Zabbix 单位换算
    Confluence6.9配置邮件服务器
    Linux内核基础优化
    Nginx跨域问题
    ssh远程登录过程中卡住
    postfix无法启动问题
    mysql-配置文件详解
    Mongodb-副本集部署
    Mongodb-安全配置优化
    Mongodb-简单部署
  • 原文地址:https://www.cnblogs.com/maoyuanwai/p/12099534.html
Copyright © 2011-2022 走看看