Vue JS 提供/注入和道具 [英] Vue JS provide/inject and Props

查看:29
本文介绍了Vue JS 提供/注入和道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与 props 相比,什么时候应该使用提供/注入.

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.

请多多指教

谢谢

推荐答案

这里有一些差异帮助我在很多情况下做出选择

Here are some differences that helped me choose in many situations

  1. 道具是反应性的,而提供/注入不是.
  2. 道具只能用于直接子组件.

来自文档:

Provide/inject 一起使用,允许祖先组件作为其所有后代的依赖注入器,无论组件层次结构有多深,只要它们在同一父链中.如果您熟悉 React,这与 React 的上下文功能非常相似.

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. 您可以使用提供/注入来设置道具的默认值.

示例:

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

这里是一篇不错的文章例如何时使用提供/注入

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

这篇关于Vue JS 提供/注入和道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆