Vue JS provide/inject and Props

本秂侑毒 提交于 2021-01-27 12:24:13

问题


When should provide/inject be used compared to props.

In my opinion props make component more meaningful.

Provide/inject makes components tightly coupled.

What are the use cases where using provide/inject is a better approach.

Please advice

Thanks


回答1:


Here are some differences that helped me choose in many situations

  1. props are reactive and provide / inject is not.
  2. props can only be used on direct child components.

From docs:

Provide / inject are used together to allow an ancestor component to serve as a dependency injector for all its descendants, regardless of how deep the component hierarchy is, as long as they are in the same parent chain. If you are familiar with React, this is very similar to React’s context feature.

  1. You can use provide / inject to set a default value for props.

example:

const Child = {
  inject: ['foo'],
  props: {
    bar: {
      default () {
        return this.foo
      }
    }
  }
}

Here is an article of a good example when to use provide / inject



来源:https://stackoverflow.com/questions/57468077/vue-js-provide-inject-and-props

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!