vue2和vue3 依赖注入

vue2:

在祖先组件里这样定义:

// Provider 
export default { 
  provide: function () { 
    return { 
      foo: this.aaaa
    } 
  } 
}

后代组件接收:

// Consumer 
export default { 
  inject: ['aaaa'] 
}

这样,我们就可以在子孙组件中通过 this.aaaa访问祖先组件提供的数据,以达到组件通讯的目的。

到了 Vue.js 3.0,除了可以继续沿用这种 Options 的依赖注入,还可以使用依赖注入的 API 函数 provide 和 inject,你可以在 setup 函数中调用它们。

在main.js中调用方式:

 在普通的父级组件给后代组件传值:

// Provider 
import { provide, ref } from 'vue' 
export default { 
  setup() { 
    const theme = ref('dark') 
    provide('theme', theme) 
  } 
}
// Consumer 
import { inject } from 'vue' 
export default { 
  setup() { 
    const theme = inject('theme', 'light') 
    return { 
      theme 
    } 
  } 
}

这里要说明的是,inject 函数接受第二个参数作为默认值,如果祖先组件上下文没有提供 theme,则使用这个默认值。

猜你喜欢

转载自blog.csdn.net/m0_57033755/article/details/130620818
今日推荐