gpt4 book ai didi

javascript - 为什么 Vue 的提供和注入(inject)功能会出现警告?

转载 作者:行者123 更新时间:2023-12-01 01:56:04 25 4
gpt4 key购买 nike

我正在考虑在项目中使用 Vue 的新提供/注入(inject)功能,但是在官方 Vue documentation 中它给出了这个警告:

provide and inject are primarily provided for advanced plugin / component library use cases. It is NOT recommended to use them in generic application code.

但是,文档没有给出原因。在“通用应用程序代码”而不是“高级插件/组件库用例”中使用提供和注入(inject)有什么危险?

在示例代码中:

// parent component providing 'foo'
var Provider = {
provide: {
foo: 'bar'
},
// ...
}

// child component injecting 'foo'
var Child = {
inject: ['foo'],
created () {
console.log(this.foo) // => "bar"
}
// ...
}

据我了解,好处是,如果您有多个嵌套子组件,您可以跳过向每个嵌套子组件传递 props,而直接在孙组件中“接收”注入(inject)的值。

如果您绕过非 react 性的默认行为“如果您传递观察到的对象”,您甚至可以使注入(inject)的值 react 性,但这里的警告对我来说是有意义的,因为您有一个 react 性变量跨越跨嵌套组件,数据不应该以这种方式传递,因此如果使用响应式对象,跟踪更改可能会变得更加困惑。

最佳答案

根据风格指南:https://v2.vuejs.org/v2/style-guide/#Implicit-parent-child-communication-use-with-caution

Props and events should be preferred for parent-child component communication, instead of this.$parent or mutating props.

An ideal Vue application is props down, events up. However, there are edge cases where prop mutation or this.$parent can simplify two components that are already deeply coupled.

The problem is, there are also many simple cases where these patterns may offer convenience. Beware: do not be seduced into trading simplicity (being able to understand the flow of your state) for short-term convenience (writing less code).

在这种特殊情况下,您本质上是使用 inject 来改变 props。您需要特别注意以下事实:在标准应用程序中使用 provide/inject 并不遵循规范方法。如果要将状态映射到组件层次结构 vuex将是首选。

关于javascript - 为什么 Vue 的提供和注入(inject)功能会出现警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51031955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com