Svelte - 将变量从父组件传递到其所有子组件
Svelte - pass variable from parent component to all its child components
我需要将数据从父组件传递到所有子组件,可能是链下的 3-4 级。为此使用事件并不是一个非常优雅的解决方案。
有没有办法定义一个组件的所有子组件都可以访问的全局变量?
我也不想用params,因为会有很多重复。
您可以使用<script context="module">
A <script>
tag with a context="module"
attribute runs once when the
module first evaluates, rather than for each component instance.
Values declared in this block are accessible from a regular <script>
(and the component markup) but not vice versa.
正是为了解决这个问题,ContextAPI
被包含在 Svelte
中
在你的 'parent' 你做
import { setContext } from 'svelte'
setContext('my-var', variable)
并且在您需要的任何 children 中,您可以执行以下操作:
import { getContext } from 'svelte'
const variable = getContext('my-var')
此技术使 my-var 成为所有后代中的变量。
请注意,此变量 不是 反应性的,如果您需要,则必须传入存储而不是常规变量。
这里是 docs
我需要将数据从父组件传递到所有子组件,可能是链下的 3-4 级。为此使用事件并不是一个非常优雅的解决方案。
有没有办法定义一个组件的所有子组件都可以访问的全局变量?
我也不想用params,因为会有很多重复。
您可以使用<script context="module">
A
<script>
tag with acontext="module"
attribute runs once when the module first evaluates, rather than for each component instance. Values declared in this block are accessible from a regular<script>
(and the component markup) but not vice versa.
正是为了解决这个问题,ContextAPI
被包含在 Svelte
在你的 'parent' 你做
import { setContext } from 'svelte'
setContext('my-var', variable)
并且在您需要的任何 children 中,您可以执行以下操作:
import { getContext } from 'svelte'
const variable = getContext('my-var')
此技术使 my-var 成为所有后代中的变量。
请注意,此变量 不是 反应性的,如果您需要,则必须传入存储而不是常规变量。
这里是 docs